联合类型和类型保护

2022-04-14  本文已影响0人  泡杯感冒灵
联合类型,就是用 | 用算符,结合两个类型
interface Bird {
  fly: boolean;
  sing: () => {};
}

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

// anima 这个变量是可以联合类型,即可以是一个Bird又可以是一个Dog
// 联合类型通过 | 来实现
// 但是联合类型变量去取值的时候,只能取到这几个类型共有的属性和方法
function trainAnimal(anima: Bird | Dog) {
  anima.fly
}
如果调用不共有的属性和方法,就会报错,因为不确定参数的类型,到底是哪个,所以调用独有的方法会报错。如果想要代码更严谨,这个时候就需要类型保护的机制。
类型保护的几种实现方法
function trainAnimal(animal: Bird | Dog) {
  // 如果我们知道animal.fly是true,那么它一定是一个bird类型。那么我们就通过as断言的方式,告诉你它就是Bird类型。
  if (animal.fly) {
    (animal as Bird).sing()
  }else {
    (anima as Dog).bark()
  }
}
function trainAnimalSecond(animal: Bird | Dog) {
  // 我判断,如果animal里有sing方法,再去调用sing方法
  // typescript也会理解这个语法的意思,就不再报错
  if ('sing' in anima) {
    animal.sing();
  } else {
    animal.bark()
  }
}
function add(first: string | number, second: string | number) {
  if (typeof first === 'string' || typeof second === 'string') {
    return `${first}${second}`;
  }
  return first + second;
}
class NumberObj {
  count:number
}

function addSecond(first: object | NumberObj, second: object | NumberObj) {
  if (first instanceof NumberObj && second instanceof NumberObj) {
    return first.count + second.count;
  }
  return 0;
}
上一篇 下一篇

猜你喜欢

热点阅读