首页 > 解决方案 > 使用 Object.keys 和减少对象键

问题描述

我正在尝试减少Object.keys,如下所示:

const example = { hello: true }
Object.keys(example).reduce((acq, key) => {
  const value = example[key]
  return acq
}, {})

出于某种原因,我收到一个类型错误example[key]

(参数)键:字符串

元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“{你好:布尔值; }'。在类型 '{ hello: boolean; 上找不到具有类型参数的索引签名。}'.(7053)

getKeys我使用具有我期望的类型的泛型创建了自己的函数:

function getKeys <T>(g: T) {
  return Object.keys(g) as (keyof T)[]
}

const example = { hello: true }
getKeys(example).reduce((acq, key) => {
  const value = example[key]
  return acq
}, {})

但是,我正在寻找是否可以不使用 wrapping Object.keys

标签: typescript

解决方案


在这种情况下,您可以为您的example变量提供 a ,如下所示,让 typescript 知道键是 type string

const example = { hello: true } as { [key: string]: any }

推荐阅读