开发中经常使用的类型转换

交叉类型及联合类型

  1. interface Bird {
  2. name: string,
  3. fly(): void
  4. }
  5. interface Person {
  6. age: number,
  7. talk(): void;
  8. }
  9. type BirdMan = Bird & Person;
  10. let chaoren: BirdMan = {
  11. name: 'lee',
  12. fly() {},
  13. age: 1,
  14. talk(){}
  15. }

对象转类型【typeof】

  1. let people = {
  2. name: "北鸟南游",
  3. age: 18
  4. }
  5. // 将people对象直接转化为type类型People
  6. type People = typeof people;

限制类型属性【keyof】

  1. type Animal = {
  2. kinds:string;
  3. name: string;
  4. legs: number;
  5. }
  6. // 获取type类型别名的key值
  7. type AnimalKey = keyof Animal; // 'kinds'|'name'|'legs'

映射类型【keyof+in】

  1. type Person = {
  2. name: string,
  3. age: number,
  4. gender: boolean
  5. }
  6. //PersonMap是从Person映射的类型,该类型各属性都变为可选
  7. type PersonMap = {
  8. [key in keyof Person]?: Person[key]
  9. }
  10. let p1:PersonMap = {name: '北鸟南游'};

内置类型

Partial
Required
Readonly
Pick

内置条件类型

Exclude
Extract
NonNullable
ReturnType
InstanceType