【Typescript 系列】第六节:联合类型

242 阅读3分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第6天,点击查看活动详情

1. 引言

哈喽,上节课我们介绍了TypeScript的交叉类型,那么这节课我们就来学习下什么事联合类型。首先我们再来回顾下什么是交叉类型

// 交叉类型
type PersonBasics = {
  name: string,
  age: number
}
type PersonOther = {
  sex: string
}
type PersonMerge = PersonBasics & PersonOther 
let newExample: PersonMerge = {
  name: '果子',
  age: 99,
}
// 报错 缺失sex 参数 ==》Type '{ name: string; age: number; }' is not assignable to type 'PersonMerge'.
// Property 'sex' is missing in type '{ name: string; age: number; }' but required in type 'PersonOther'.


let newExample2: PersonMerge = {
  name: '果子',
  age: 99,
  sex: '男'
}
// 正常


let newExample3: PersonMerge = {
  name: '果子',
  age: 99,
  sex: '男',
  say: 'halou'
}
// 报错:Type '{ name: string; age: number; sex: string; say: string; }' is not assignable to type 'PersonMerge'.
  Object literal may only specify known properties, and 'say' does not exist in type 'PersonMerge'.

从上述例子我们就能看出来,交叉类型意味着是类型的“集合”必须是交叉的类型值都存在且不能存在类型集合以外属性,这就是交叉类型。


言归正传:接下来我们介绍联合类型 什么是联合类型? 简单来说就是:联合类型 = 类型A | 类型B的 “或集”

2. 含义

联合类型(Union Types)可以通过管道(|)将变量设置多种类型,赋值时可以根据设置的类型来赋值, ==注意:只能赋值指定的类型,如果赋值其它类型就会报错。==

3. 作用

  1. 表示可以为多种类型中的一种,当我们需要一个变量同时具备多种类型的场景时,就可以使用联合类型申明,==它的使用类型只能属于联合类型中的其中一种类型==。
  2. 基础例子看例一。
  3. 当我们使用联合类访问方法时会发生什么事情呢?请看例二,我们可以从例子二中发现,当访问函数需要使用形参时候,需要通过类型检测工具判断具体类型,才能保持运行正确。还有很多类型守卫语法:①in 关键字,②typeof 关键字,③instanceof关键字,④自定义类型保护的类型谓词 作用:可执行运行时检查的一种表达式,用于确保该类型在一定的范围内。这里我们下期在单独介绍。
  4. 像例句五中当extends 可赋值语句中的主语句为接受泛型变量,传入对应类型为联合类型时候就会触发TypeScript的一种==分布式条件类型== ++==注意:返回结果是个联合对象类型,要是当extends判断后,返回的是true | false 最终值是==++ type IsBoolean = true | false // type IsBoolean = boolean

4. 例子

// 例子1
let Demo: string | number
Demo = 5 // ok
Demo = 'studyTs' // ok
Demo = true // error:不能将类型“boolean”分配给类型“string | number”

// 例子二
function greet(persons: string | string[]): string{
    // 真值缩小/类型缩窄:因为联合类型存在多种类型值,直接使用传入的不确定属性值,Ts语法检测会拦截
    if(typeof person === 'string'){
        return `hello,${person}`
    }else if(Array.isArray(person)){
        return '是个数组'
    }
    throw new Error('unable To find')
}
// 例子三
type HttpMethod = 'Get' | 'Post' | 'Put' | 'Delete' | 'Update'
let action:HttpMethod = 'GET' // 报错:该字面量类型不存在类型httpMethod 联合类型中

// 例句四:
type Name = {
    name: string
}
type Age = {
    age: number
}
let a: Name | Age = {name: '李四'} // ok
let b: Name | Age = {age: 12} // ok
let c: Name | Age = {name: '小明',age: 55} // ok
let d: Name | Age = {name: '小明',age: 55,sex: '男'}  // 错误:sex 属性不存在Name 与 Age 的联合类型中
// 例句五:
type UnionType = 'A' | 12 | true
type Judge<T> = T extends string ? never : T
type example = Judge<UnionType> // type example = true | 12

5. 总结

实际使用生活场景中,联合类型出现的频率比较多,根据不同场景他对结果也有不同影响,有兴趣的同学可以自己实际操作下,才能发现其中的问题。