我试图编写一个函数来返回对象中的值数组
let obj = {
a: 1,
b: 2,
c: 3,
}
const r = Object.keys(obj).map((key) => {
let val = obj[key]
return val
})
在这里,TS编译器显示了一个错误,说
元素隐式具有"any"类型,因为类型的表达式"string"不能用于索引类型"{a:number;b:number,c:"number;}'。没有具有"string"类型参数的索引签名在类型"{a:数字;b:数字;c:数字;}"上找到。ts(7053(
我无法理解它的含义,但我认为它与key
是字符串有关。所以我尝试了这个
let obj = {
a: 1,
b: 2,
c: 3,
}
const r = Object.keys(obj).map((key) => {
let val = obj[key as keyof typeof obj] // the error now is gone
return val
})
console.log('r', r)
现在没有错误。我不太清楚为什么。我只知道keyof
会在obj
上产生允许的属性名称类型,但我不知道typeof
在中有什么用途
Typescript推断obj
对象的类型为:
type Obj = {
a: number
b: number
c: number
}
这也可以表示为:
type Obj = {[key in 'a' | 'b' | 'c']: number};
CCD_ 6是CCD_。然而,当您使用Object.keys(obj)
时,typescript会将这里的返回类型推断为string[]
,而不是('a' | 'b' | 'c')[]
。这就是它抱怨No index signature with a parameter of type 'string' was found on type '{ a: number; b: number; c: number; }'
的原因——因为您不能使用任何string
来查找obj
中的值,而是需要使用特定的键。
keyof
操作符将类型作为输入,并返回所提供的键。您需要typeof
的原因是推断对象的类型(否则您将执行keyof obj
,typescript无法理解,因为obj
不是类型(
keyof typeof obj
推断为"a" | "b" | "c"
键-https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html#keyof-和查找类型
类型-https://mariusschulz.com/blog/type-queries-and-typeof-in-typescript#typescripts-类型查询