如何限制TypeScript函数返回类型为已有字面量类型的指定子集
实现方案
你可以通过TypeScript内置的Extract工具类型实现这个需求,具体代码如下:
export const MyType = [ 'one', 'two', 'three', 'four' ] as const; export type MyType = typeof MyType[number]; // 从MyType联合类型中筛选仅包含'one'和'two'的子类型 type AllowedType = Extract<MyType, 'one' | 'two'> function myFunc(): AllowedType { // 此时返回值仅允许为'one'或'two',返回其他值会触发类型校验报错 return 'one' }
如果你担心硬写字面量出现拼写错误,也可以基于原始的常量数组派生子集类型,保证类型和原始定义完全一致:
// 基于原始常量数组定义允许的取值范围,避免拼写不一致 const allowedValues = [MyType[0], MyType[1]] as const type AllowedType = typeof allowedValues[number] function myFunc(): AllowedType { return 'two' }
内容的提问来源于stack exchange,提问作者Sergino
相关产品推荐
相关产品推荐

