typescript进阶(Typescript advanced)

环境准备

参考基础《TODO》

联合类型和类型保护

interface Bird {
  fly: boolean;
  sing: () => {};
}

interface Dog {
  fly: boolean;
  bark: () => {};
}
// 联合类型
function trainAnimal(animal: Bird | Dog) {
  if (animal.fly) {
    // 1、类型断言
    (animal as Bird).sing();
  }
}

function trainAnimal2(animal: Bird | Dog) {
  // 2、in || typeof || instanceof
  if ("sing" in animal) {
    animal.sing;
  }
}
————————

Environmental preparation

Refer to basic todo

Joint type and type protection

interface Bird {
  fly: boolean;
  sing: () => {};
}

interface Dog {
  fly: boolean;
  bark: () => {};
}
// 联合类型
function trainAnimal(animal: Bird | Dog) {
  if (animal.fly) {
    // 1、类型断言
    (animal as Bird).sing();
  }
}

function trainAnimal2(animal: Bird | Dog) {
  // 2、in || typeof || instanceof
  if ("sing" in animal) {
    animal.sing;
  }
}