typescript进阶2
联合类型
let num : string | number = 1
keyof
将一个属性的属性名全部提取出来当做联合类型
interface Person {
name: string
age: number
}
type PersonKeys = keyof Person
const p1: PersonKeys = 'name'
const p2: PersonKeys = 'age'
const p3: PersonKeys = 'height'
Record<K, T>
将K中的所有属性的值转化为T类型
type Record<K extends keyof any, T> = {
[P in K]: T;
};
type Methods = 'POST' | 'GET' | 'DELETE'
type typeMetod = Record<Methods, any>
Partial
type Partial<T> = {
[P in keyof T]?: T[P]
}
interface Person {
name: string
age: number
}
const person1: Person = {}
const person2: Partial<Person> = {}
const person3: Partial<Person> = { name: 'xiaodu' }
const person4: Partial<Person> = { height: 1.88 }
Required 必须的, 必须有
type Required<T> = { [P in keyof T]-?: T[P] };
interface Ren {
name?: string,
age?: number
}
type Rentype = Required<Ren>
const niuheng : Rentype = {
name: '牛恒'
}
Pick<T, K>
type Pick<T, K extends keyof T> = {
[P in K]: T[P];
};
interface Niuheng {
name: string,
age: number,
sex: string,
}
let person: Pick<Niuheng, 'name' | 'age'> = {
name: '牛恒',
age: 23,
}
Readonly 将传入的属性变为只读 (浅层的)
interface Xiaohu {
name: string,
age: number,
girlFriend:{
name: string,
age: number
}
}
type ReadOnlyXiaohu = Readonly<Xiaohu>
const XiaoHuA : ReadOnlyXiaohu = {
name: 'xiaohu',
age: 18,
girlFriend: {
name: 'xiaomei',
age: 18
}
}
XiaoHuA.name = 'sss'
XiaoHuA.age = 20
XiaoHuA.girlFriend.age = 20
Exclude<T,U>
type Exclude<T, U> = T extends U ? never : T;
type T = Exclude<1|2|3|4|5, 3|4>
type Extract<T, U> = T extends U ? T : never;
type T = Extract<1|2|3|4|5, 3|4>
Omit<T,K >没有内置
interface Person {
name: string,
age: number,
sex: string,
}
let person: Omit<Person, 'name'> = {
age: 1,
sex: '男'
}
NonNullable
type NonNullable<T> = T extends null | undefined ? never : T;
type T = NonNullable<string | string[] | null | undefined>;
ReturnType
type ReturnType<T extends (...args: any[]) => any> = T extends (...args: any[]) => infer R ? R : any;
type T1 = ReturnType<() => string>;
type T2 = ReturnType<(s: string) => void>;
参考资料:
https://blog.csdn.net/dajuna/article/details/117958613
https://zhuanlan.zhihu.com/p/115428938
https://juejin.cn/post/6844903684422254606#heading-28