You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何限制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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 07:39:02