Typescript学习笔记(13) ----- 联合类型和类型保护

基本概念

  • 联合类型:该类型要么属于A要么属于B,用代码来表示就是:
function test(name: A | B){

}

这个就称之为A和B的联合。

  • 类型保护:对typescript类型报错的情况进行进一步处理,使其不会报错

用一个简单的例子来说明这种情况:


image.png

有Bird和Dog两种类型,由于两个类型都具有fly,所以这样是不会报错的。
但ts不能确定传进来是Bird类型还是Dog类型,所以会抛出一个错。

遇到这个情况,需要使用断言进行类型保护
确保代码不会抛错

常用的类型保护的方式

  • 使用断言进行类型保护
    使用断言并且配合一些逻辑判断进行类型保护
//使用断言进行类型保护
function trainAnimal(animal: Bird | Dog){
  if(animal.fly){
    (animal as Bird).sing()
  }else{
    (animal as Dog).bark()
  }
}
  • 使用in语句进行类型保护
//使用关键字in进行类型保护
function trainAnimal2(animal: Bird | Dog){
  if('sing' in animal){
    animal.sing()
  }else{
    animal.bark()
  }
}
  • 使用type of进行类型保护
function add(a:number|string,b:number|string){
  if(typeof a === 'string' || typeof b === 'string'){
    return `${a}${b}`
  }
  return a + b
}
  • instance of 适合引用类型
//使用instance of 进行类型保护

class numberObject{
  count:number
}

function objectAdd(a:numberObject|object,b:numberObject|object){
  if(a instanceof numberObject && b instanceof numberObject){
    return a.count + b.count
  }
  return 0
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。