我有這個介面,我基本上想要一個哈希陣列。像這樣的東西(可能不正確):
export interface EntitySpec {
originId: EntityType;
mandatoryProperties: Array<{ [key: string]: string }>;
}
但我想像這樣應用界面:
const spec: EntitySpec = {
originId: 1,
mandatoryProperties: {
'code': 'sad',
'name': 'this',
'comment': 'here',
},
};
但我明白了:輸入'{代碼:字串;}' 不可分配給型別 '{ [key: string]: string; }[]'。我將如何正確地做到這一點?
uj5u.com熱心網友回復:
這是因為mandatoryProperties是一個Array物件。把它包起來[],你應該沒問題:
const spec: EntitySpec = {
originId: 1,
mandatoryProperties: [
{
'code': 'sad',
'name': 'this',
'comment': 'here',
}
]
};
uj5u.com熱心網友回復:
如果要分配objectto mandatoryProperties,請Array<>從介面中洗掉,如下所示:
export interface EntitySpec {
originId: EntityType;
mandatoryProperties: { [key: string]: string };
}
const spec: EntitySpec = {
originId: 1,
mandatoryProperties: {
'code': 'sad',
'name': 'this',
'comment': 'here',
},
};
否則將mandatoryProperties陣列內部包裝如下:
export interface EntitySpec {
originId: EntityType;
mandatoryProperties: Array<{ [key: string]: string }>;
}
const spec: EntitySpec = {
originId: 1,
mandatoryProperties: [{
'code': 'sad',
'name': 'this',
'comment': 'here',
}],
};
uj5u.com熱心網友回復:
你mandatoryProperties是一個物件,而不是一個陣列。你需要洗掉它Array<>
export interface EntitySpec {
originId: EntityType;
mandatoryProperties: { [key: string]: string };
}
但是,如果您需要一個陣列,那么您可以[]在最后添加:
export interface EntitySpec {
originId: EntityType;
mandatoryProperties: { [key: string]: string }[];
}
const spec: EntitySpec = {
originId: 1,
mandatoryProperties: [
{
'code': 'sad',
'name': 'this',
'comment': 'here',
}
]
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/464469.html
標籤:javascript 打字稿
