TypeScript 4.3.5使用模板字面量索引对象报TS7053错误如何解决
问题原因
你使用的TypeScript 4.3.5版本不支持模板字面量的自动类型推导,${val}Light 会被TS识别为通用string类型,而Colors类型没有定义string类型的索引签名,因此触发TS7053报错。
解决方法
方案1:手动断言模板字符串为合法key
改动最小,直接告诉TS拼接出的字符串一定是Colors的合法属性:
const getLightColor = (val: BaseColors) => { return colors[`${val}Light` as keyof Colors]; };
如果需要更严格的类型校验,也可以单独定义带Light后缀的key类型:
type LightColorKey = `${BaseColors}Light` const getLightColor = (val: BaseColors) => { return colors[`${val}Light` as LightColorKey]; };
方案2:升级TypeScript版本
TypeScript 4.5及以上版本已经支持模板字面量的自动类型推导,升级到4.5+版本后,你原有代码不需要任何改动就能正常通过类型校验。
方案3:给Colors添加索引签名(不推荐)
如果不想修改现有逻辑也不想升级TS,可以给Colors增加string类型的索引签名,但是会丢失部分类型校验能力:
type Colors = { [key: string]: string; red: string; blue: string; redLight: string; blueLight: string; };
内容的提问来源于stack exchange,提问作者Bernat Duran Pons
相关产品推荐
相关产品推荐

