-
A | B
是并集
的意思,既可以是A
也可以是B
,也可以是A和B的交集
type A = {
name:string
}
type B = {
age: number
}
type C = A | B
const a1:C = {
age:18
}
const a2:C = {
name:"frank"
}
const a3:C = {
name:"frank",
age:18
}
- 但是当 type A = string | number 时就类型特性就不好用了,因此需要进行
类型收窄
- typeof:缺点是只支持基本类型,不具体
type A = string | number
const fn = (a:A) => {
if(typeof a === "number"){
a.toFixed()
}else{
a.split()
}
}
- instanceof,缺点是不支持string,number等基本类型,不支持TS独有的类型
const fn = (a: Date | Date[]) =>{
if(a instanceof Date){
}else if(a instanceof Array){
}
}
-
in
,缺点是只适用于部分对象
type Person = {
name: string
}
type Animal = {
action: string
}
const fn = (a:Person | Animal) =>{
if('name' in a){
a.name
}else if('action' in a){
a.action
}
}
- 类型谓词
is
,缺点是麻烦
type Rect = {
height: number
width: number
}
type Circle = {
center: [number,number]
radius: number
}
const fn = (a: Rect | Circle) => {
if(isRect(a)){
a.height
}else {
a.center
}
}
// is这里是必须是普通函数
function isRect(x: Rect | Circle): x is Rect{
return 'height' in x && 'width' in x
}
function isCircle(x: Rect | Circle): x is Circle{
return 'center' in x && 'radius' in x
}
- 可辨别联合:加一个
可辨别的字段
,这个字段只能是基本类型
,且可区分
type Circle = {
kind: "Circle"
center: [number,number]
}
type Square = {
kind: "Squrae"
sideLength: number
}
const fn = (a: string | number | Circle | Square) => {
if(typeof a === "string"){
}else if(typeof a === "number"){
}else if(a.kind === "Circle"){
}else if(a.kind === "Squrae"){
}
}
- 强制断言
as