Skip to content
Advertisement

Typescript Interface specification with hash

I have this interface where I basically want to have an array of hashes. Something like this (propably not correct):

export interface EntitySpec {
  originId: EntityType;
  mandatoryProperties: Array<{ [key: string]: string }>;
}

But I want to apply the interface like this:

const spec: EntitySpec = {
  originId: 1,
  mandatoryProperties: {
    'code': 'sad',
    'name': 'this',
    'comment': 'here',
  },
};

But I get this: Type ‘{ code: string; }’ is not assignable to type ‘{ [key: string]: string; }[]’. How would I do this properly?

Answer

It’s because mandatoryProperties is an Array of objects. Wrap that into [] and you should be fine:

const spec: EntitySpec = {
  originId: 1,
  mandatoryProperties: [
    {
      'code': 'sad',
      'name': 'this',
      'comment': 'here',
    }
  ]
};
Advertisement