元素隐式具有 'any' 类型,因为类型 'string' 的表达式不能用于索引类型 'Type'

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Type'

我正在尝试 trim 从 REST API 返回的对象数组中的值。

这是我期待的对象的interface

interface IProduct {
  productId: number;
  qty: number;
  code: string;
  customer: string;
  description: string;
}

我试图遍历对象数组和trim对象的所有值。

products.forEach(record => {
  if (record) {
    Object.keys(record).map(key => {
      record[key] = record[key].trim();
    });
  }
});

我收到以下错误。

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'IProduct'.
No index signature with a parameter of type 'string' was found on type 'IProduct'.

我试过向对象添加索引签名,但没有成功。 [key: string]: string 还有 key: {[index: string]: string}.

有没有我遗漏的东西,我认为这足以让 TS 编译器停止抱怨。

这是对象的引用。

const products: Product[] = [
  {
    productId: 1,
    qty: 100,
    code: 'code',
    customer: 'customer',
    description: 'the description',
  },
  {
    productId: 2,
    qty: 102,
    code: 'code',
    customer: 'customer',
    description: 'the description',
  },
];

非常感谢

Object.keys 的定义是:

interface ObjectConstructor {
  keys(o: object): string[];
  keys(o: {}): string[];
}

这是因为你可以这样写代码:

const object = {
  productId: 1,
  qty: 100,
  code: 'code',
  customer: 'customer',
  description: 'the description',
  someOtherKey: 'foo', // extra key here
};
const product: IProduct = object;
const keys = Object.keys(product); // keys contains someOtherKey

要修复您的错误,您可以使用类型断言:

products.forEach(record => {
  if (record) {
    (Object.keys(record) as (keyof IProduct)[]).map(/* ... */);
  }
});

但是,如果您知道不会有额外的键,则可以添加此重载:

declare global {
  interface ObjectConstructor {
    keys<K extends PropertyKey>(o: Record<K, unknown>): K[];
  }
}
// declare global can only be in a module, so if the file isn't
// a module already you'll need to add this
export {};

这样,您就不需要类型断言,但这在技术上不是类型安全的。