gpt4 book ai didi

typescript - 使用枚举键入接口(interface)字段的索引签名?

转载 作者:行者123 更新时间:2023-12-04 11:15:30 24 4
gpt4 key购买 nike

我可以用对象类型表示法描述索引类型限制,如下所示:

enum Enum {
A = 0,
B = 1,
}

type EnumMap = {
[P in Enum]: string;
}

但是,令人惊讶的是,在接口(interface)中使用索引符号时似乎不可能做到这一点:
enum Enum {
A = 0,
B = 1,
}

interface EnumMap {
[P in Enum]: string;
}

错误是:

A computed property name must be of type 'string', 'number', 'symbol', or 'any'.



有什么原因吗?根据定义,TypeScript 中的枚举只能有字符串或数字值(甚至两者都有,但不推荐这样做),我认为枚举本身可以像它列出的所有值的联合类型一样工作。

进一步调查,我还发现,在以下示例中, EnumValues有类型 number , 而不是(我所期望的) 0 | 1 .再次,为什么会这样?
const Enum = {
A: 0,
B: 1
};

type EnumKeys = keyof typeof Enum;
type EnumValues = typeof Enum[EnumKeys];

最佳答案

关于错误:

interface EnumMap {
[P in Enum]: string;
}
Enum 是 TypeScript 中的一种特殊数据结构,不可分配给 string | number | symbol .
考虑这个例子:
const key = <T extends string | number | symbol>(t: T) => t

key(Enum) // error
另外, enum有特殊行为。
看这个例子:
const enm = (t: Enum) => t

// Argument of type 'typeof Enum' is not assignable to parameter of type 'Enum'
enm(Enum) // error
所以即使在 Enum 之间也有区别和 typeof Enum .
让我们回到我们的问题。
直到 TS 4.4不允许在接口(interface)中使用联合作为索引签名。
考虑这个没有 enum 的例子:
interface EnumMap {
[P in 'a'|'b']: string; // error
}
因此,它是关于 TS 限制而不是关于枚举。
至于第二种情况:
const Enum = {
A: 0,
B: 1
};

type EnumKeys = keyof typeof Enum;
type EnumValues = typeof Enum[EnumKeys];
这是因为 const Enum是可变的。
为了获得 1|0 ,你应该让它不可变:
const Enum = {
A: 0,
B: 1
} as const; // special syntax

type EnumKeys = keyof typeof Enum;
type EnumValues = typeof Enum[EnumKeys]; // 0 | 1

关于typescript - 使用枚举键入接口(interface)字段的索引签名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53508709/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com