联合类型和类型保护

联合类型

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

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

function traingAnimal(animal: Bird | Dog) {
    animal.sing() // 报错
}

联合类型只能访问到公有属性和方法。

交叉类型

多种类型的集合,联合对象将具有所联合类型的所有成员

interface People {
  age: number,
  height: number
}
interface Man{
  sex: string
}
const xiaoman = (man: People & Man) => {
  console.log(man.age)
  console.log(man.height)
  console.log(man.sex)
}
xiaoman({age: 18,height: 180,sex: 'male'});
类型保护
类型断言

如果明确知道对象类型,可以使用as转换成具体对象实例。

/// 类型保护1:类型断言
function traingAnimal(animal: Bird | Dog) {
  if (animal.fly) {
    (animal as Bird).sing()
  } else {
    (animal as Dog).bark()
  }
}
in语法

如果指定属性和方法在某个实例对象中,就可以在对应语句块中调用具体实例对象的方法。

/// 类型保护2:in语法
function traingAnimal(animal: Bird | Dog) {
  if ('sing' in animal) {
    animal.sing()
  } else {
    animal.bark()
  }
}
typeof 语法
/// 类型保护3:typeof 语法
function traingAnimal(first:number|string,second:number|string) {
  if (typeof first === 'string' || typeof second === 'string') {
   return `${first}${second}`
  } else {
    return first + second
  }
}
instanceof 语法

instanceof 做类型判断只能识别 class 对象类型而不能识别 interface 类型。


class NumberObj {
  count: number
}

// 类型保护4:instanceof 语法
function addSecond(first: object | NumberObj, second: object | NumberObj) {
  if (first instanceof NumberObj && second instanceof NumberObj) {
    return first.count + second.count
  }
  return 0
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值