繁体   English   中英

枚举值的类型

[英]Type of enum values

我可以通过以下方式获取表示接口键的类型:

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"
enum E { A = "a", B = "b" }
const e: keyof typeof E;

游乐场示例

模板文字运算符的帮助下,枚举的值列表可以推断为一种类型:

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

参考文章: 动态获取枚举的值(免责声明:作者在这里)

事实上,枚举的名称本身就是其值类型联合的别名。 以下代码演示:

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 WaterTypekeyof number相同,这绝对不是您想要的。

有趣的事实: keyof typeof WaterType是一个谎言。 WaterType的键实际上是"Lake"|"River"|"Ocean"|"Creek"|0|1|2|3 (例如WaterType["Creek"]==3WaterType[3]=="Creek" .)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM