如何在类型注释中使用数字枚举作为索引?

时间:2019-01-24 17:49:12

标签: typescript

我想使用数字枚举作为对象中的索引类型。

enum Weekday {
    Monday = 0,
    Tuesday = 1,
    Wednesday = 2,
    Thursday = 3,
    Friday = 4,
    Saturday = 5,
    Sunday = 6
};

const isWeekend: { [day: Weekday]: boolean } = {
    [Weekday.Monday]: false,
    [Weekday.Tuesday]: false,
    [Weekday.Wednesday]: false,
    [Weekday.Thursday]: false,
    [Weekday.Friday]: false,
    [Weekday.Saturday]: true,
    [Weekday.Sunday]: true,
};

此代码无法通过消息进行类型检查:

  

索引签名参数类型必须为“字符串”或“数字”。

我知道一些解决方法。如果我将isWeekend的类型更改为{ [day: number]: boolean },它将进行编译,但是类型会降低一些精度。

如何在不更改isWeekend定义的情况下为Weekday提供更精确的类型?

1 个答案:

答案 0 :(得分:1)

我自己解决了这个问题。我应该一直使用day in Weekday而不是day: Weekday。以下代码有效:

enum Weekday {
    Monday = 0,
    Tuesday = 1,
    Wednesday = 2,
    Thursday = 3,
    Friday = 4,
    Saturday = 5,
    Sunday = 6
};

const isWeekend: { [day in Weekday]: boolean } = {
    [Weekday.Monday]: false,
    [Weekday.Tuesday]: false,
    [Weekday.Wednesday]: false,
    [Weekday.Thursday]: false,
    [Weekday.Friday]: false,
    [Weekday.Saturday]: true,
    [Weekday.Sunday]: true,
};