相关疑难解决方法(0)

如何将 Typescript 类型定义为字符串字典,但具有一个数字“id”属性

现有的 JavaScript 代码有“记录”,其中 id 是数字,其他属性是字符串。尝试定义这种类型:

type t = {
    id: number;
    [key:string]: string
}
Run Code Online (Sandbox Code Playgroud)

给出错误 2411 id 类型编号无法分配给字符串

typescript

16
推荐指数
1
解决办法
1278
查看次数

如何创建具有索引签名和不同类型的固定属性的 TypeScript 接口?

从旧的 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)

json interface typescript index-signature

5
推荐指数
1
解决办法
1065
查看次数

标签 统计

typescript ×2

index-signature ×1

interface ×1

json ×1