1. typeof
在 TypeScript中,typeof 操作符可以用来获取一个变量的声明,或是对象的类型
//例子1interface People {name: string;age: number;}const variableDai: People = { name: 'coolFish', age: 24 };type formDai= typeof variableDai; // -> People//例子2function toArray(x: number): Array<number> {return [x];}type Func = typeof toArray; // -> (x: number) => number[]
小结:要注意的是,例子1中我们定义了一个常量 variableDai 然后获取他的类型,赋值给了类型 formDai。
2. keyof
keyof 操作符可以用来一个对象中的所有 key 值, 返回的是这些key值得联合类型。
interface Person {name: string;age: number;}type allKey = keyof Person; // "name" | "age"
当然我们可以利用这个特性来做一些特殊的操作,例如遍历一个数组,返回一个数组所拥有的所有属性的联合类型
interface Person {name: string;age: number;}type key = keyof Person[];// "length" | "toString" | "pop" | "push" | "concat" | "join"
type K3 = keyof { [x: string]: Person }; // string | number// 因为这里的键是索引类型,所以是 string | number
3. in
in 用来遍历枚举类型
type Keys = 'a'|'b'|'c'type obj = {[p in Keys]: any}//{ a: any, b: any, c: any }
4. infer
在条件类型语句中,可以用infer 声明一个类型变量,并且对它进行使用。
//返回数组的第一项type Head<T extends Array<any>> = T extends [head : infer H, ...rest : any[]] ? H : never;// 测试用例type H0 = Head<[]> // nevertype H1 = Head<[1]> // 1type H2 = Head<[3, 2]> // 3
上例的原理是,我们用infer定义一个类型变量为第一项,然后类型收窄,就获得了第一项。
5. extends
当我们定义的泛型不想过于灵活,或者想继承某些类的时候,我们可以通过 extends 关键字添加泛型约束
interface mustLength {length: number;}function mustTakeLength<T extends mustLength>(arg: T): T {console.log(arg.length);return arg;}mustTakeLength(3)// Error, number doesn't have a .length propertyloggingIdentity({length: 10, value: 3});//10
我们定义了一个 mustLength 的接口,然后 入参受该接口约束,必须有一个 length 属性。否则就会报错
type User = {id: number;kind: string;};// T assignable Userfunction makeCustomer<T extends User>(u: T): T {return {...u,id: u.id,kind: 'customer'}}// 用扩展运算符将多余参数返回即可。
6. Partial
Partial
type Partial<T> = {[P in keyof T]?: T[P];};interface User {name:string,age:number,department:string}type optional = Partial<User>/**type optional = {name?: string | undefined;age?: number | undefined;department?: string | undefined;}**/
7. Required
Required
8. Readonly
Readonly
9. Record
Record
type Record<K extends keyof any, T> = {[P in K]: T;};// 将K 中有类型的属性进行遍历,再将每个 Key 赋值 T类型 实例
type petsGroup = 'dog' | 'cat' | 'fish';interface IPetInfo {name:string,age:number,}type IPets = Record<petsGroup, IPetInfo>;const animalsInfo:IPets = {dog:{name:'dogName',age:2},cat:{name:'catName',age:3},fish:{name:'fishName',age:5}}
