其他分享
首页 > 其他分享> > ts类型保护

ts类型保护

作者:互联网

interface Bird {
  fly: boolean;
  sing: () => {};
}
interface Dog {
  fly: boolean;
  bark: () => {};
}
// 类型断言的方式

function trainAnimal(animal: Bird | Dog){
  if(animal.fly){
    (animal as Bird).sing()
  }else {
    (animal as Dog).bark()
  }
}

// in 语法来做类型保护
function trainAnimalSecond(animal: Bird | Dog){
  if('sing' in animal){
    animal.sing()
  }else {
    animal.bark()
  }
}

// typeof 语法来做类型保护
function add(first: string | number, second: string | number){
  if(typeof first === 'string' || second === 'string'){
    return `${first}${second}`
  }else {
    return first + second
  }
}

// 使用instanceof 语法来做类型保护
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
}

标签:string,ts,保护,second,animal,类型,NumberObj,Bird,first
来源: https://www.cnblogs.com/sinceForever/p/16242047.html