typescript学习系列3:联合类型和类型保护

194 阅读1分钟

1.联合类型:

通过"|"来实现一个联合类型,如下代码:

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

interface Dog{
  fly:Boolean;
  bark:()=>{}
}

function trainAnimals(animals:Bird | Dog){
  
}

2.类型保护以及常用的类型保护的方式:

1.联合类型只会对共有属性或者方法予以提示

  • 联合类型中的,ts代码提示只能给出共有的方法或者属性

2.类型保护的常用方式:

  • 类型断言:
interface Bird{
  fly:Boolean;
  sing:()=>{}
}

interface Dog{
  fly:Boolean;
  bark:()=>{}
}

function trainAnimals(animals:Bird | Dog){
  if(animals.fly)
  {
    // animals.sing();直接写ts会报错飘红
    (animals as Bird).sing();
  }
  else
  {
    // animals.bark()
    (animals as Dog).bark();
  }
}
  • "in"语法类型保护
function trainAnimalsSecond(animals:Bird | Dog){
  if("sing" in animals)
  {
    animals.sing();
  }
  else
  {
    animals.bark();
  }
}
  • typeof类型保护
function ass(first:string | number,second:string | number){
  if(typeof first === "string" || typeof second === "string"){
    return `${first}${second}`;
  }
  return first + second;//因为有string类型,没有上面的if内容,直接return ts会飘红
}
  • 利用class以及instanceof属性
function addSecond(first:object | NumberObj,second:object | NumberObj){
  // return first.count + second.count; //直接return会飘红,因为ts检测object上不一定有count属性
  if(first instanceof NumberObj && second instanceof NumberObj){
    return first.count + second.count;
  }
  return 0;
}