5

从遗留 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 界面输入这种格式吗?

4

1 回答 1

5

这是TypeScript Dictarray 概念的变体。

作弊修复是告诉 TypeScript 一切都很好,并且你知道自己在做什么:

interface ISomeObject {
    [index: string]: number[];
    // @ts-ignore: I'm creating a Dictarray!
    general: {
        [index: string]: number;
    };
}

编译器将正确推断返回类型,在这种情况下是数字:

let x: ISomeObject;

const a = x.general['idx'];
const b = x['idx'];

链接的文章有更多信息,但这是您具体情况的要点。

于 2018-11-29T09:58:07.593 回答