'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?



Solution 1:[1]

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',
    }
  ]
};

Solution 2:[2]

If you want to assign an object to mandatoryProperties, remove Array<> from an interface as follows:

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

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

else wrap the mandatoryProperties inside an array as follows:

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

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

Solution 3:[3]

Your mandatoryProperties is an object, not an array. You need to remove that Array<>

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

However, if you need an array,then you can add [] at the end:

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

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Some random IT boy
Solution 2 Shubham Waje
Solution 3 bill.gates