枚举值的类型

时间:2018-10-26 20:41:12

标签: typescript typescript3.0

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

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"

3 个答案:

答案 0 :(得分:0)

enum E { A = "a", B = "b" }
const e: keyof typeof E;

Playground example

答案 1 :(得分:0)

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

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"。)

答案 2 :(得分:0)

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