typescript 文档阅读笔记-Unions and Intersection Types

Union Types

用来组合不同类型

let name: string | number

Unions with Common Fields

如果某个值的类型是一个联合类型。那么我们只能访问他们公共的变量。
可以试试使用类型断言来解决,前提是你明确知道该值是什么类型。也可以通过条件语句先进行判断是某种类型,然后再使用

interface Bird {
  fly(): void;
  layEggs(): void;
  state: 1
}

interface Fish {
  swim(): void;
  layEggs(): void;
  state: 2;
  code: 2;
}

declare function getSmallPet(): Fish | Bird;

let pet = getSmallPet();
pet.layEggs();

// Only available in one of the two possible types 报错
// swim 不是 Bird、Fish 共有的,当返回类型时 Bird 时,下面的代码就会报错。为了避免这种情况,
// 如果某个值的类型时一个联合类型。那么我们只能访问他们公共的变量。
pet.swim();
// 解决办法
(pet as Fish).swim()
// 联合类型下, state 的值为 1 | 2,可以使用该值判断当前值的类型是 Bird 还是 Fish,然后就可以使用该类型的 code
if(pet.state === 1) console.log(pet.code)

Intersection Types

可以将多个 type 聚合到一个 type 中

interface Person {
    name: string
    age: number
}

interface Student {
    school: string
    score: number
}

interface User {
    base: Person & Student
}

const user: User = {
    base: {
        name: 'long',
        age: 1,
        school: 'fdsl',
        score: 100
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值