我有以下Javascript对象:
{
"dataMap":{
"2027":{
"userId":2027,
"code":"abcdef",
"title":"abcdef",
"questions":1
}
"2028":{
"userId":2028,
"code":"abcdef",
"title":"abcdef",
"questions":1
}
}
}
它包含另一个对象dataMap,其中包含其他ojbects。有人可以通过告诉我如何为dataMap对象创建接口来帮助我吗?
我想要的是有一个界面,我可以输入:
var a = b.dataMap[2027].userId // okay and allowed
var a = b.dataMap[2027].xxxyId // gives a typescript error
答案 0 :(得分:1)
您可以使用带索引签名的界面:
interface User {
userId: number;
code: string;
title: string;
questions: number;
}
interface DataMap {
[index: number]: User;
}
对于您的特定示例,数据映射再次包含在对象中:
interface DataMapContainer {
dataMap: DataMap;
}
var b: DataMapContainer = { "dataMap": { ... } };
b.dataMap[2027].userId; // okay
b.dataMap[2027].xxx; // error
另请参阅:TypeScript interface for object with arbitrary numeric property names?