TypeScript:为什么这里有一个"keyof"可以解决这个问题



我试图编写一个函数来返回对象中的值数组

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-类型查询

相关内容

最新更新