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

如何用导入的数组构建TypeScript字符串字面量类型?

问题:从JS配置文件生成字符串字面量联合类型

场景

配置文件为next.config.js,无法转为TypeScript文件,代码如下:

module.exports = {
    locales: ['en', 'fr']
}

问题重现

在TypeScript项目中导入该配置,尝试推导字符串字面量类型:

import config from "config.js"

const tempDefaultLocales = [...config.locales] as const
export type Language = typeof tempDefaultLocales[number]

此时Language的类型是string,而非预期的"en" | "fr"。但如果直接硬编码数组并使用as const,就能得到正确的联合类型:

const locales = ["en","fr"] as const
type Language = typeof locales[number]

需求

希望在不修改配置文件格式、不硬编码的前提下解决该问题,避免维护两份语言配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 06:35:27