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?
CodePudding user response:
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',
}
]
};
CodePudding user response:
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',
}],
};
CodePudding user response:
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',
}
]
};