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

如何用JSON文件为TypeScript枚举赋值?解决类型不匹配错误

解决TypeScript枚举使用JSON赋值的类型错误

TypeScript字符串枚举要求成员值必须是字符串字面量或其他枚举成员,直接导入的JSON属性会被推断为宽泛的string类型,不符合枚举的类型约束,所以会抛出Type 'string' is not assignable to type 'number'的错误(这里错误提示有误导性,实际是字符串字面量约束的问题)。

下面提供两种可行的解决方法:

方案一:用as const断言JSON类型

通过as const让TypeScript将JSON的属性值识别为具体的字面量类型,满足枚举的赋值要求:

// TS 5.0+支持该导入语法,旧版可改用require
import en from './en.json' assert { type: 'json' };
// 旧版TS写法:const en = require('./en.json') as const;

// 将JSON转为常量类型,固定属性值为字面量
const localizedLabels = en as const;

export enum AccountSettings {
  accountManagement = localizedLabels.account_management,
  managementOfRelatives = localizedLabels.management_of_relatives,
}

方案二:用对象模拟枚举(更适配多语言场景)

如果不需要枚举的特殊特性(比如反向映射),用对象模拟枚举是更灵活的选择,完全支持从外部JSON取值:

import en from './en.json' assert { type: 'json' };

// 定义常量对象,as const确保属性值为字面量类型
export const AccountSettings = {
  accountManagement: en.account_management,
  managementOfRelatives: en.management_of_relatives,
} as const;

// 同步生成对应的类型,实现和枚举一致的类型约束
type AccountSettings = typeof AccountSettings[keyof typeof AccountSettings];

使用时和枚举完全一致,还能避免枚举的类型限制问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 09:15:01