有点旧,但我觉得我可以为此添加一些清晰度。
准确答案
interface MyObject {
id: number;
name: string;
}
interface MyExactData {
[key: string]: MyObject;
}
let userTestStatus: MyExactData = {
"0": { "id": 0, "name": "Available" },
"1": { "id": 1, "name": "Ready" },
"2": { "id": 2, "name": "Started" }
};
但上面不是我们通常做对象数组的方式,你会使用javaScript中简单的原生数组。
interface MyObject { // define the object (singular)
id: number;
name: string;
}
let userTestStatus_better: MyObject[] = [
{ "id": 0, "name": "Available" },
{ "id": 1, "name": "Ready" },
{ "id": 2, "name": "Started" }
];
只需将[] 添加到我们的界面即可为所述对象的数组提供类型。
并内联做到这一点
let userTestStatus_inline: {id:number, name:string}[] = [
{ "id": 0, "name": "Available" },
{ "id": 1, "name": "Ready" },
{ "id": 2, "name": "Started" }
];
我会使用界面,因为您有一些可定义、可理解和可重用的东西。如果您需要进行更改,您可以对一个界面进行更改,打字稿会报告您的界面代码不匹配。