I'm trying to reduce Object.keys
, like this:
const example = { hello: true }
Object.keys(example).reduce((acq, key) => {
const value = example[key]
return acq
}, {})
For some reason I am getting a type error under example[key]
(参数)键:字符串 元素隐式地具有“ any”类型,因为类型“ string”的表达式不能用于索引类型“ {hello:boolean; }'。 在类型“ {{hello:boolean;”中找不到参数类型为“ string”的索引签名。 }'。(7053)
I created my own getKeys
function with a generic that has the typings I'd expect:
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
}, {})
However I'm looking if this is possible without wrapping Object.keys
.
In this case you could provide a for your
example
variable as shown below to let typescript know that the keys are of typestring
.