迭代对象时键入键

Type key when iterating an object

我有这个功能可以根据 API 响应调整 React 组件的初始状态。

export const getInitialStateByData = (initialData: TApiResponseData, fields: TFormFields) => {
  for (const [key] of Object.entries(initialData)) {
    if (!fields.includes(key)) {
      delete initialData[key]
    }
  }

  return initialData
}

我遇到了这个错误Argument of type 'string' is not assignable to parameter of type 'TLocaleKey'.ts(2345) const key: string

我试过了for (const [key]: [TLocaleKey] of Object.entries(initialData)) ... The left-hand side of a 'for...of' statement cannot use a type annotation. 错误。

ts playground

输入密钥的任何解决方案?提前致谢。

Object.entries 的类型如下(这就是为什么 key 被键入为 string 的原因):

interface ObjectConstructor {
    ...

    /**
     * Returns an array of key/values of the enumerable properties of an object
     * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
     */
    entries<T>(o: { [s: string]: T } | ArrayLike<T>): [string, T][];

    /**
     * Returns an array of key/values of the enumerable properties of an object
     * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
     */
    entries(o: {}): [string, any][];

    ...
}

reference

因此,我们将无法利用类型参数;元组 entries returns 中的第一项将始终为 string 类型。旁白:如果你好奇,this is why.

没有办法转换在 for 循环中声明的变量(据我所知)。因此,您必须转换数组:

for (const [key] of (Object.entries(initialData) as [TLocaleKey, string][])) { ... }

TypeScript Playground