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

如何创建仅接受特定类型值的TypeScript枚举?

解决方案

首先明确:默认数字枚举的成员值是数字(0、1、2...),你提到的weatherParams是枚举成员名称的字符串联合类型,下面分场景给出可行方案:

1. 自动同步枚举与目标类型(推荐)

不需要手动定义weatherParams,直接从枚举生成对应的字符串联合类型,既能保证两者完全一致,还能避免手动维护的错误:

enum forecastEnum {
    pressure,
    humidity,
    feels_like,
}

// 自动生成枚举成员名称的联合类型,等价于你定义的weatherParams
type weatherParams = keyof typeof forecastEnum;
// 此时weatherParams的类型就是 'pressure' | 'humidity' | 'feels_like'

2. 手动指定类型并约束枚举成员

如果必须保留手动定义的weatherParams,可以通过编译时类型检查确保枚举的所有成员名称都属于这个类型——一旦枚举新增/删除不符合weatherParams的成员,TypeScript会直接报错:

type weatherParams = 'humidity' | 'pressure' | 'feels_like';

enum forecastEnum {
    pressure,
    humidity,
    feels_like,
}

// 编译时断言:若枚举有成员名称不在weatherParams中,此处会报错
type _AssertEnumMatchesType = Exclude<keyof typeof forecastEnum, weatherParams> extends never ? true : false;
// 触发断言检查(无需使用该变量,仅用于编译时校验)
const _check: _AssertEnumMatchesType = true;

3. 让枚举值转字符串时符合目标类型

如果需要把枚举的数字值转换成对应的字符串名称,同时让返回值类型严格为weatherParams,可以写一个工具函数:

type weatherParams = 'humidity' | 'pressure' | 'feels_like';

enum forecastEnum {
    pressure,
    humidity,
    feels_like,
}

function getParamName(param: forecastEnum): weatherParams {
    return forecastEnum[param] as weatherParams;
}

// 使用示例
const name = getParamName(forecastEnum.pressure); // name的类型为weatherParams

关键说明

  • 数字枚举的默认数值键(0、1、2...)会被完整保留,完全不影响排序等操作。
  • 上述方案均为编译时校验,不会生成额外运行时代码。

内容的提问来源于stack exchange,提问作者Kiszuriwalilibori

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 21:24:23