Pick
Pick 接受两个类型参数,T 表示要从中选择属性的类型,K 表示选择的属性名的联合类型。通过映射类型,遍历联合类型 K 中的每个属性,然后从类型 T 中选择相应的属性。
type Pick<T, K extends keyof T> = {
  [P in K]: T[P];
};
interface Example {
  a: number;
  b: string;
  c: boolean;
}
type PickedType = Pick<Example, 'a' | 'b'>;
// PickedType 的类型为 { a: number, b: string }
 
Omit
我们使用了 Exclude 来排除 K 中的属性名,然后再通过 Pick 来选择剩余的属性。
type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;
interface Example {
  a: number;
  b: string;
  c: boolean;
}
type OmittedType = Omit<Example, 'a' | 'b'>;
// OmittedType 的类型为 { c: boolean }
 
协变
let arr1: number[] = [1, 2, 3];
let arr2: (number | string)[] = arr1;
// 允许将 number[] 赋值给 (number | string)[]
 
逆变
type Printer<T> = (value: T) => void;
let numberPrinter: Printer<number> = (value: number) => {
  console.log(value);
};
let anyPrinter: Printer<any> = numberPrinter;
// 允许将 Printer<number> 赋值给 Printer<any>
 
Partial
在 TypeScript 中,Partial<T> 是一个内置的工具类型,它将类型 T 中的所有属性变为可选属性。
type MyPartial<T> = {
  [P in keyof T]?: T[P];
};
 
interface Example {
  a: number;
  b: string;
  c: boolean;
}
type PartialExample = MyPartial<Example>;
// PartialExample 的类型为 { a?: number, b?: string, c?: boolean }
 
interface 与 type 有何区别
共性:
都用于定义对象或函数的类型
区别:
- 声明使用的关键字不一样
 - 合并性
 
- interface具有合并特性
 
interface Car {
  brand: string;
  speed: number;
}
interface Car {
  model: string;
}
// 合并后的 Car 接口为 { brand: string; speed: number; model: string; }
 
- type不具和并行,多次声名会导致冲突
 
type Car = {
  brand: string;
  speed: number;
};
type Car = {
  model: string;
};
// Error: 无法重新定义 "Car"
 

 



















