如何仅通过包含枚举的变量引用对应枚举类型?
问题:如何引用第三方库导出的枚举类型?
第三方库导出代码
第三方库没有直接导出枚举,而是导出了一个指向枚举的变量:
enum Size { S, M, L } export const sizeType: typeof Size = Size;
自有代码需求
我们需要在自有代码中声明属性类型为原枚举Size,但只能导入sizeType变量:
import { sizeType } from '...'; interface Props { size: /* 此处应写什么来等价于'Size'? */ } const props: Props = { size: sizeType.S }; props.size = sizeType.L;
已尝试但无效的写法
size: typeof sizeType;错误:Type 'Size' is not assignable to type 'typeof Size'.
size: typeof sizeType['S'];错误:Type 'Size.L' is not assignable to type 'Size.S'.
size: InstanceType<typeof sizeType>;错误:Type
typeof Size' does not satisfy the constraint 'abstract new (...args: any) => any.
正确解决方案
使用typeof sizeType[keyof typeof sizeType]即可获取等价于原枚举Size的类型:
import { sizeType } from '...'; interface Props { size: typeof sizeType[keyof typeof sizeType]; } const props: Props = { size: sizeType.S }; props.size = sizeType.L; // 正常通过类型检查
原理说明
typeof sizeType获取的是枚举对象的类型(包含所有枚举键值对的对象类型)keyof typeof sizeType得到枚举所有键的联合类型('S' | 'M' | 'L')- 通过
typeof sizeType[keyof typeof sizeType]取出所有枚举值的联合类型,这就是原枚举Size的类型
内容的提问来源于stack exchange,提问作者Michael Liu
相关产品推荐
相关产品推荐

