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

时间:2018-11-29 09:44:26

标签: json typescript interface index-signature

从旧版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界面​​输入此格式?

1 个答案:

答案 0 :(得分:2)

这是http://localhost:81的变体。

作弊修补程序是告诉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'];

链接的文章提供了更多信息,但这是您的特定情况的要旨。

相关问题