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

如何修复TypeScript的TS(7053)隐式any类型索引错误?

TypeScript 索引类型错误(ts(7053)、ts(2698))修复方案

问题代码

type CleanAddres = {
    // 其他属性
    city?: string;
}
type AddressNewData = {
    // 其他属性
    id?: number;
};

function getAddres(addres: AddressNewData[], cleanedAddres: CleanAddres) {
    const newAddres = Object.keys(cleanedAddres).map((key, i) => {
        const { id } = addres[i] as Clients.AddresNewData;
        return {
            id: id || 0,
            ...cleanedAddres[key] // 触发ts(7053)错误
        };
    });
}

错误提示

The element is implicitly of type 'any', since an expression of type 'string' cannot be used for indexing of type 'CleanAddres'. An index signature with a parameter of type "string" was not found in the 'CleanAddres' type. ts(7053)

尝试过的方案

  • 方案1:
map((key: keyof cleanedAddres, i)
  • 方案2:
const newAddres = Object.keys(cleanedAddres).map((key, i) => {
    // ...
    const key1 = key as keyof cleanedAddres
    return {
        id: id || 0,
        ...cleanedAddres[key1] // 触发ts(2698)错误
    };
});

修复方案

问题根源在于Object.keys()返回类型是string[],TypeScript无法确认这些字符串是CleanAddres的合法键;另外你尝试的keyof cleanedAddres是错误的,应该用类型名CleanAddres而非变量名。

以下是修正后的代码:

type CleanAddres = {
    // 示例属性,可根据实际情况补充
    city?: string;
    street?: string;
}
type AddressNewData = {
    // 示例属性,可根据实际情况补充
    id?: number;
    contact?: string;
};

function getAddres(addres: AddressNewData[], cleanedAddres: CleanAddres) {
    // 将Object.keys的结果断言为CleanAddres的键数组
    const newAddres = (Object.keys(cleanedAddres) as Array<keyof CleanAddres>).map((key, i) => {
        // 避免addres[i]为undefined导致的运行时错误
        const addressItem = addres[i];
        const id = addressItem?.id || 0;
        // 此时cleanedAddres[key]类型会被正确推断,不会报错
        return {
            id,
            ...cleanedAddres[key]
        };
    });
    return newAddres;
}

修复说明

  1. 类型断言修正:把Object.keys(cleanedAddres)断言为Array<keyof CleanAddres>,告诉TypeScript这些键都是CleanAddres的合法索引,解决ts(7053)错误。
  2. 变量名拼写修正:修正了代码中AddresNewData的拼写错误(应为AddressNewData),如果Clients.AddresNewData是命名空间类型,同样需要确保拼写一致。
  3. 运行时安全:增加addressItem?.id的可选链判断,避免数组越界导致的undefined解构错误。

内容的提问来源于stack exchange,提问作者Александр Кос

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 16:16:13