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

如何从字符串数组推导联合类型?TypeScript as const报错解决

解决方法

下面几种方案可以帮你把map后的字符串数组推导成目标联合类型:

方法1:给JSON文件添加类型声明文件

如果你的data.json内容固定,直接给它写个类型声明,让TypeScript明确每个item的code是具体字面量:

创建data.json.d.ts文件,内容如下:

declare const _data: { code: 'fr-fr' | 'es-es' }[];
export default _data;

然后修改原代码,无需as const:

import _data from './data.json'

const locales = _data.map(item => item.code)

export type DataType = typeof locales[number] // 自动推导为 'fr-fr' | 'es-es'

方法2:手动断言map的返回类型

直接把map的结果断言成包含具体字面量的数组类型,跳过默认的宽泛推断:

import _data from './data.json'

const locales = _data.map(item => item.code) as ('fr-fr' | 'es-es')[]

export type DataType = typeof locales[number] // 得到 'fr-fr' | 'es-es'

方法3:提前定义联合类型并约束数据类型

先明确写出目标联合类型,再用它约束导入的_data类型,map后的结果类型自然符合预期:

// 先定义目标联合类型
export type LocaleCode = 'fr-fr' | 'es-es'

import _data from './data.json'

// 约束_data的类型
const locales = (_data as Array<{ code: LocaleCode }>).map(item => item.code)

export type DataType = LocaleCode // 直接复用定义好的类型,或用typeof locales[number]也可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 06:01:02