1、keyof的作用
作用:用来获取接口,对象,类等的所有属性名组成的联合类型。
1.1获取接口的属性的联合类型:
type person = {
name: string,
age: number,
};
type p = keyof person; // a = name | age
interface Animal {
name: string,
sex: string,
}
type animal = keyof Animal; // animal = name | sex
1.2获取对象属性的联合类型:
这里需要借助typeof先获取对象的类型
const info = {
name: 'tom',
age: 12,
sex: 'man'
}
// 第一步利用typeof先获取对象的类型
type t = typeof info;
/**上面的代码输出:type t = {
name: string;
age: number;
sex: string;
}
**/
// 第二步利用keyof获取类型t的属性组成联合类型
type c = keyof t; // c = name | age | sex
//上面的两步可以合并成
type c = keyof typeof info;
1.3获取类的属性组成的联合类型:
class Demo {
name!: string;
age!: number
constructor() {
}
init() {}
}
type demo = keyof Demo; // demo = name | age | init
2、typeof的作用
作用:根据已有的值,获取对应值的类型
获取值为数组的类型:
const arr = [1,2,3,4];
type arr1 = typeof arr // arr1 = number[]
获取值为对象的类型:
const info = {
name: 'tom',
age: 12,
sex: 'man'
}
type t = typeof info;
/**
输出:
type t = {
name: string;
age: number;
sex: string;
}
**/