现有的 JavaScript 代码有“记录”,其中 id 是数字,其他属性是字符串。尝试定义这种类型:
type t = {
id: number;
[key:string]: string
}
Run Code Online (Sandbox Code Playgroud)
给出错误 2411 id 类型编号无法分配给字符串
从旧的 api 我得到一个 JSON 响应,如下所示:
const someObject = {
"general": {
"2000": 50,
"4000": 100,
"8000": 200,
},
"foo": [
0,
1,
2,
],
"bar": [
5,
7,
],
"baz": [
8,
9,
],
};
Run Code Online (Sandbox Code Playgroud)
请记住,除“general”之外的所有索引都是动态的,可能不在响应中,我无法为每个属性键入但必须使用索引签名。
我想通过 typescript@2.9.2 来实现:
interface ISomeObject {
general: {
[index: string]: number;
};
[index: string]?: number[];
}
Run Code Online (Sandbox Code Playgroud)
因为general总是会在响应,但其他指标可能会或可能不会在那里。
我面临的问题:
[index: string]?: number[]可选的,因为它会抱怨这里使用数字作为值。[index: string]: number[]将覆盖的定义,general: number因此 tsc 会抱怨:
Property 'general' of type '{ [index: string]: number; }' is …Run Code Online (Sandbox Code Playgroud)