创建一个采用枚举参数的类型

Creating a type that takes enum argument

我正在尝试使用 Record 类型创建可重复使用的类型。

enum MyKeys {
  ALPHA = 'ALPHA',
  BETA = 'BETA',
  GAMMA = 'GAMMA',
}

interface MyValues {
  in: any[];
  out: any[];
}

type Case<T> = Record<T, MyValues>;

理想情况下,我可以使用 Case<MyKeys> 而不是 Record<MyKeys, MyValues>

Type 'T' does not satisfy the constraint 'string | number | symbol'.

Type 'T' is not assignable to type 'symbol'

类型参数 T 需要限制为有效的索引类型:

type Case<T extends string> = Record<T, MyValues>;

可用于键的唯一有效类型是字符串、数字和符号。 TypeScript 为这种名为 PropertyKey.

的联合提供了一个内置别名

内置 Record 类型将只接受其中之一。这就是为什么您的类型构造函数也需要具有相同的约束。

type Case<T extends PropertyKey> = Record<T, MyValues>;