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

JS转TS代码时出现Element implicitly has an 'any' type错误的修复方法

修复TypeScript中对象索引的类型错误

我将一段JavaScript代码转换为TypeScript后,遇到了如下类型错误,原代码及错误信息如下:

原TypeScript代码

const toCamelCase = (rows: any[]) => {
  return rows.map((row) => {
    const replaced = {};

    for (let key in row) {
      const camelCase = key.replace(/([-_][a-z])/gi, ($1) =>
        $1.toUpperCase().replace('_', '')
      );
      replaced[camelCase] = row[key];
    }

    return replaced;
  });
};

错误提示

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 '{}'.ts(7053)

错误出现在replaced[camelCase] = row[key];这一行,以下是几种可行的修复方案:


方案1:给replaced添加字符串索引签名

直接声明replaced为带有字符串索引的对象,明确它的键为字符串类型,值可以是任意类型:

const toCamelCase = (rows: any[]) => {
  return rows.map((row) => {
    const replaced: { [key: string]: any } = {};

    for (let key in row) {
      const camelCase = key.replace(/([-_][a-z])/gi, ($1) =>
        $1.toUpperCase().replace('_', '')
      );
      replaced[camelCase] = row[key];
    }

    return replaced;
  });
};

方案2:使用Record类型简化声明

TypeScript内置的Record类型可以更简洁地定义键为字符串、值为任意类型的对象:

const toCamelCase = (rows: any[]) => {
  return rows.map((row) => {
    const replaced: Record<string, any> = {};

    for (let key in row) {
      const camelCase = key.replace(/([-_][a-z])/gi, ($1) =>
        $1.toUpperCase().replace('_', '')
      );
      replaced[camelCase] = row[key];
    }

    return replaced;
  });
};

方案3:泛型优化(类型严谨性提升)

如果需要转换后的对象保留原对象值的类型,而非使用any,可以通过泛型和类型推导实现更精确的类型约束:

// 定义驼峰命名的类型转换工具
type CamelCase<S extends string> = S extends `${infer Prefix}-${infer Char}${infer Rest}`
  ? `${Prefix}${Uppercase<Char>}${CamelCase<Rest>}`
  : S extends `${infer Prefix}_${infer Char}${infer Rest}`
  ? `${Prefix}${Uppercase<Char>}${CamelCase<Rest>}`
  : S;

type CamelCaseObject<T> = {
  [K in keyof T as CamelCase<string & K>]: T[K];
};

const toCamelCase = <T extends Record<string, any>>(rows: T[]) => {
  return rows.map((row) => {
    const replaced = {} as CamelCaseObject<T>;

    for (let key in row) {
      const camelCase = key.replace(/([-_][a-z])/gi, ($1) =>
        $1.toUpperCase().replace('_', '')
      ) as CamelCase<string & keyof T>;
      replaced[camelCase] = row[key];
    }

    return replaced;
  });
};

这种方案能让转换后的对象拥有准确的类型提示,适合对类型严谨性要求较高的场景。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 10:30:45