keyof
const foo = {
name: 'tom',
age: 18
}
const field = 'age'
console.log(foo[field]) // error 元素隐式具有 "any" 类型,因为类型为 "string" 的表达式不能用于索引类型
// 解决
console.log(foo[field as keyof typeof foo])
keyof 介绍
JavaScript 通过 Object.keys()
获取对象的所有属性键值,而 typescript 主要关注的是类型操作,通过 keyof
操作符可以获取对象中的所有键类型组成的联合类型。
示例:
type Person = {
id: number;
name: string;
};
type P = keyof Person; // 'id' | 'name'
keyof
操作符得到的是 Person
类型的所有键值类型即 'id'
和 'name'
三个字面量类型组成的联合类型 'id' | 'name'
。
在获取对象类型的键之后,我们就可以通过类似属性访问的语法来访问该键对应的值的类型。
type P1 = Person["id"] // number
type P2 = Person["id" | "name"] // string | number
type P3 = Person[keyof Person] // string | number
可扩展接口类型
interface Foo {
[key: string]: any
}
const foo: Foo = {
name: 'tom',
age: 18
}
console.log(foo.name)
any 类型
interface Foo {
[key: string]: any
}
const foo: any = {
name: 'tom',
age: 18
}
console.log(foo.name)
修改 tsconfig.json
{
"compilerOptions": {
"suppressImplicitAnyIndexErrors": true,
}
}