背景
系统中有多种类型的组件,但是其中有一些组件在类型名称上有共性,并且它们的性质上也有共性,为了将这些有共性的类型筛选出来,需要有一种方式可以通过特定的类型名筛选出这些枚举值并组成一个联合类型,用在需要判断的地方
实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| enum WidgetTypes { typeA = 'typeA', typeB = 'typeB', special_typeC = 'special_typeC',
special_typeD = 'special_typeD',
special_typeE = 'special_typeE', }
type SpecialTypeKeys = { [K in keyof typeof WidgetTypes]: typeof WidgetTypes[K] extends `special_${string}` ? K : never; }[keyof typeof WidgetTypes];
type SpecialWidgetTypes = Pick<typeof WidgetTypes, SpecialTypeKeys>[keyof Pick<typeof WidgetTypes, SpecialTypeKeys>];
|