【发布时间】:2019-03-31 15:32:24
【问题描述】:
我可以通过以下方式获得表示接口键的类型:
interface I { a: string; b: string; }
const i: keyof I; // typeof i is "a" | "b"
有没有办法类似地获得表示枚举值的类型?
enum E { A = "a", B = "b" }
const e: ?; // typeof e is "a" | "b"
【问题讨论】:
我可以通过以下方式获得表示接口键的类型:
interface I { a: string; b: string; }
const i: keyof I; // typeof i is "a" | "b"
有没有办法类似地获得表示枚举值的类型?
enum E { A = "a", B = "b" }
const e: ?; // typeof e is "a" | "b"
【问题讨论】:
在template literal 运算符的帮助下,可以将枚举的值列表推断为类型:
enum E { A = "a", B = "b" }
type EValue = `${E}`
// => type EValue = "a" | "b"
const value: EValue = "a" // => ✅ Valid
const valid: EValue = "b" // => ✅ Valid
const valid: EValue = "?" // => ? Invalid
参考文章:Get the values of an enum dynamically (免责声明:作者在此)
【讨论】:
事实上,枚举的名称本身就是其值类型联合的别名。以下代码演示:
enum WaterType {
Lake = 0,
Ocean = 1,
River = 2,
Creek = 3,
};
let xxx: 0|1|2|3 = 2;
let yyy: WaterType = xxx; // OK
let zzz: 0|1|2|3 = yyy; // OK
枚举有点令人困惑,因为枚举的名称在某些上下文中指的是类型(如0|1|2|3),但在其他上下文中它指的是同名的对象。 WaterType 对象与此对象类似:
const WaterTypeObject = {
Lake : 0 as 0,
Ocean : 1 as 1,
River : 2 as 2,
Creek : 3 as 3,
};
而typeof WaterType 与typeof WaterTypeObject 几乎相同:
let aaa: typeof WaterType = WaterType;
let bbb: typeof WaterTypeObject = aaa; // OK
let ccc: typeof WaterType = bbb; // OK
在需要类型的上下文中,WaterType 表示0|1|2|3,但您可以改为使用typeof WaterType 来获取枚举对象的类型:
// VS code reports: type WaterTypeString = "Lake" | "River" | "Ocean" | "Creek"
type WaterTypeString = keyof typeof WaterType;
// VS code reports: type WaterTypeNumbers = WaterType
// which really means type WaterTypeNumbers = 0|1|2|3
type WaterTypeNumbers = (typeof WaterType)[WaterTypeString];
请确保不要写“keyof Enum”,例如keyof WaterType和keyof number一样,肯定不是你想要的。
有趣的事实:keyof typeof WaterType 是一个谎言。 WaterType 的键实际上是"Lake"|"River"|"Ocean"|"Creek"|0|1|2|3(例如WaterType["Creek"]==3 和WaterType[3]=="Creek"。)
【讨论】:
enum E { A = "a", B = "b" }
const e: keyof typeof E;
【讨论】:
e 的类型是 "A" | "B"(枚举值),而不是 "a" | "b"(枚举值)。
const e: E 不行吗?编辑:我在playground 中看到自动完成功能有效,但出现“不可分配”警告。
E 是枚举类型。我正在寻找它的值的类型,它是字符串类型"a" 和"b" ("a" | "b") 的联合。