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

使用模板字面量类型定义Record触发TS错误及Prettier识别问题

问题解决:TypeScript模板字面量类型错误与Prettier识别问题

TypeScript类型错误修复

错误原因

你当前的PropEventSource类型用string & keyof Type获取的是枚举的键名(ReactionsCheckbox、SettingsCheckbox),而非枚举的实际值(reactionsEnabled、settingsEnabled)。同时,string & keyof Type会把原生字符串的所有原型方法(比如charAt、concat)都纳入联合类型,导致你赋值的字符串无法匹配这个混乱的类型集合。

修复代码

直接基于枚举值的联合类型拼接模板字面量即可:

enum InputFieldName {
    ReactionsCheckbox = 'reactionsEnabled',
    SettingsCheckbox = 'settingsEnabled',
}
// 直接使用枚举值的联合类型拼接Checkbox后缀
type PropEventSource = `${InputFieldName}Checkbox`;

const inputMap: Record<InputFieldName, PropEventSource> = {
    [InputFieldName.ReactionsCheckbox]: 'reactionsEnabledCheckbox',
    [InputFieldName.SettingsCheckbox]: 'settingsEnabledCheckbox',
}

const fieldName = inputMap[InputFieldName.ReactionsCheckbox];

console.log('fieldName', fieldName);

如果需要保留泛型复用性,可以这样写:

enum InputFieldName {
    ReactionsCheckbox = 'reactionsEnabled',
    SettingsCheckbox = 'settingsEnabled',
}
// 泛型约束为字符串值的枚举/对象,获取其值的联合类型后拼接
type PropEventSource<Type extends Record<string, string>> = `${Type[keyof Type]}Checkbox`;

const inputMap: Record<InputFieldName, PropEventSource<typeof InputFieldName>> = {
    [InputFieldName.ReactionsCheckbox]: 'reactionsEnabledCheckbox',
    [InputFieldName.SettingsCheckbox]: 'settingsEnabledCheckbox',
}

Prettier识别问题修复

原因

旧版本Prettier对TypeScript的模板字面量类型语法支持不完善,导致无法正确解析该代码行。

解决方法

  • 升级Prettier到2.8.0及以上的稳定版本,新版本已完善对TypeScript模板字面量类型的语法支持。
  • 检查项目根目录的Prettier配置文件(如.prettierrc、prettier.config.js),确保未禁用TypeScript相关语法解析规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 13:02:22