关于keyof和typeof的个人理解,有不妥之处,欢迎指正:
最近在学习TS的类型体操,发现还是要理论和实战结合,理论这一块就不用说了,可以看TS的官方文档,了解一些基本的概念和用法。实战的话可以在这个网站上练习(github.com/type-challe…) 1、keyof的作用
作用:用来获取接口,对象,类等的所有属性名组成的联合类型。
获取接口的属性的联合类型:
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
获取对象属性的联合类型:
这里需要借助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;
获取类的属性组成的联合类型:
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;
}
**/