联合类型
interface Bird {
name: string;
fly(): void;
}
interface Person {
name: string;
talk(): void;
}
type BirdPerson = Bird | Person;
let p: BirdPerson = { name: "zfeng", fly() {} };
let p1: BirdPerson = { name: "zfeng", talk() {} };
交叉类型
interface Bird {
name: string;
fly(): void;
}
interface Person {
name: string;
talk(): void;
}
type BirdPerson = Bird & Person;
let p: BirdPerson = { name: "zhufeng", fly() {}, talk() {} };
内置条件类型
type Extract<T, U> = T extends U ? T : never;
type Exclude<T, U> = T extends U ? never : T;
type NonNullable<T> = T extends null | undefined ? never : T;
type N = NonNullable<string | number | null | undefined>;// 删除null和undifined;
type E = Exclude<string | number, string>; // 排除关系 输出 string;
type I = Extract<string | number, string>; // 包含关系 输出 number;
获取函数返回值的类型
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : any;
function getUserInfo(name: string, age: number) {
return { name, age };
}
type UserInfo = ReturnType<typeof getUserInfo>;
const userA: UserInfo = {
name: "zhufeng",
age: 10,
};
获取函数参数的类型
type Parameters<T> = T extends (...args: infer R) => any ? R : any;
function getUserInfo(name: string, age: number) {
return { name, age };
}
type T1 = Parameters<typeof getUserInfo>; // [name: string, age: number]
提取
// pick 的原理
// type Pick<T, K extends keyof T> = { [P in K]: T[P] };
interface Person {
name: string;
age: number;
visiable: boolean;
}
type Person1 = Pick<Person, 'name'|'age'> ;
取反
interface Person {
name: string;
age: number;
visiable: boolean;
}
type Person1 = Pick<Person, 'name'|'age'> ;
type Exclude<T, U> = T extends U ? never : T;
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
type Person2 = Omit<Person, "age">;
交集
type Extract<T, U> = T extends U ? T : never;
type Intersection<T extends object, U extends object> = Pick<
T,
Extract<keyof T, keyof U> & Extract<keyof U, keyof T>
>;
type C1 = { name: string; age: number; visible: boolean };
type C2 = { name: string; age: number; sex: number };
type C3 = Intersection<C1, C2>;
差集
type Exclude<T, U> = T extends U ? never : T;
type Diff<T extends object, U extends object> = Pick<
T,
Exclude<keyof T, keyof U>
>;
type C1 = { name: string; age: number; visible: boolean };
type C2 = { name: string; age: number; sex: number };
type C11 = Diff<C1, C2>;
并集
// Compute的作用是将交叉类型合并
type Compute<A extends any> = A extends Function ? A : { [K in keyof A]: A[K] };
type Omit<T, K> = Pick<T, Exclude<keyof T, K>>;
type Merge<O1 extends object, O2 extends object> = Compute< O1 & Omit<O2, keyof O1>>;
type C1C2 = Merge<C1, C2>;