【发布时间】:2019-05-01 08:07:08
【问题描述】:
从一个旧的 api 我得到一个 JSON 响应,如下所示:
const someObject = {
"general": {
"2000": 50,
"4000": 100,
"8000": 200,
},
"foo": [
0,
1,
2,
],
"bar": [
5,
7,
],
"baz": [
8,
9,
],
};
请记住,除“general”之外的所有索引都是动态的,可能不在响应中,我无法为每个属性键入,但必须使用索引签名。
我想通过 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 界面输入这种格式吗?
【问题讨论】:
-
你为这个可能令人困惑的问题提出了一个很好的标题!
-
@John rubber duck problem solving 的力量 ;) 谢谢你的客气话。
标签: json typescript interface index-signature