从遗留 api 我得到一个 JSON 响应,如下所示:
const someObject = {
"general": {
"2000": 50,
"4000": 100,
"8000": 200,
},
"foo": [
0,
1,
2,
],
"bar": [
5,
7,
],
"baz": [
8,
9,
],
};
请记住,除“一般”之外的所有索引都是动态的,可能不在响应中,我无法为每个属性键入,但必须使用索引签名。
我想通过 typescript@2.9.2 来实现:
interface ISomeObject {
general: {
[index: string]: number;
};
[index: string]?: number[];
}
就像general
在响应中一样,但其他索引可能存在也可能不存在。
我面临的问题:
- 我不能将其
[index: string]?: number[]
设为可选,因为它会抱怨此处将数字用作值。 [index: string]: number[]
将覆盖的定义,general: number
因此 tsc 将抱怨:Property 'general' of type '{ [index: string]: number; }' is not assignable to string index type 'number[]'.`
我什至可以使用 TypeScript 界面输入这种格式吗?