TypeScript索引类型报错7053:原因分析与修复方案咨询
TypeScript错误7053:索引类型不匹配问题的原因与修复
问题代码
export type Options = Record<string, string> export type CheckboxValue<T extends Options> = Partial< Record<keyof T, boolean> > export type Checkbox<T extends Options> = { value: CheckboxValue<T> } export function Checkbox<T extends Options>({ value, }: Checkbox<T>) { return value } export type FilterProps<T extends Options> = { options: T value: string[] } export function Filter<T extends Options>( props: FilterProps<T>, ) { const { value = [] } = props const mappedValue = (() => { const contextValue: string[] = value const result = {} for (const item of contextValue) { /* * Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'. * No index signature with a parameter of type 'string' was found on type '{}'.(7053) */ result[item] = true } return result })() return Checkbox({value: mappedValue}) }
运行时触发错误:Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'. No index signature with a parameter of type 'string' was found on type '{}'.(7053)
错误原因
- 空对象的类型推断限制:初始化
const result = {}时,TypeScript默认推断其类型为{}(无属性的空对象),该类型没有定义string类型的索引签名,因此无法用string类型的item作为索引赋值,触发7053错误。 - 类型不兼容隐患:
Filter接收的value是string[],但最终要传递给Checkbox的value是Partial<Record<keyof T, boolean>>,两者类型未做约束,即使解决索引问题,也可能存在类型不匹配的风险。
修复方案
方案一:严格约束输入类型(推荐)
修改FilterProps的value类型,确保它只能是T的键组成的数组,同时给result指定正确的目标类型,从源头避免类型错误:
export type Options = Record<string, string> export type CheckboxValue<T extends Options> = Partial< Record<keyof T, boolean> > export type Checkbox<T extends Options> = { value: CheckboxValue<T> } export function Checkbox<T extends Options>({ value, }: Checkbox<T>) { return value } // 约束value为T的键数组 export type FilterProps<T extends Options> = { options: T value: Array<keyof T> } export function Filter<T extends Options>(props: FilterProps<T>) { const { value = [] } = props const mappedValue = (() => { // 指定result为目标类型 const result: CheckboxValue<T> = {} for (const item of value) { result[item] = true } return result })() return Checkbox({ value: mappedValue }) }
方案二:使用类型断言兼容现有输入
如果无法修改FilterProps的value类型,可以给result添加索引签名,并通过类型断言转换为目标类型(需自行保证value元素为T的键):
export type Options = Record<string, string> export type CheckboxValue<T extends Options> = Partial< Record<keyof T, boolean> > export type Checkbox<T extends Options> = { value: CheckboxValue<T> } export function Checkbox<T extends Options>({ value, }: Checkbox<T>) { return value } export type FilterProps<T extends Options> = { options: T value: string[] } export function Filter<T extends Options>(props: FilterProps<T>) { const { value = [] } = props const mappedValue = (() => { // 添加string类型的索引签名 const result: Record<string, boolean> = {} for (const item of value) { result[item] = true } // 断言为目标类型,需确保value元素都是T的键 return result as CheckboxValue<T> })() return Checkbox({ value: mappedValue }) }
内容的提问来源于stack exchange,提问作者Pavel Perevezencev
相关产品推荐
相关产品推荐

