导航
type A1 = number
type B1 = string
type C1 = A1 | B1
const c1: C1 = 32
type A2 = { name: string }
type B2 = { age: number }
type C2 = A2 | B2
const c2: C2 = {
name: 'Lance',
}
为什么会有类型收窄:有联合类型就代表有多种类型可能,在实际传值后就有可能要做类型区分
const f1 = (a: number | string) => {
// a.toFixed() 类型“string | number”上不存在属性“toFixed”
// a.split(',') 类型“string | number”上不存在属性“split”
if (typeof a === 'string') { // 类型收窄
a.split(',')
} else {
a.toFixed(2)
}
}
缺点
const f1 = (a: Array<Date> | Date) => {
if (a instanceof Date) {
a.toISOString()
} else if (a instanceof Array) {
a[0].toISOString()
} else {
throw new Error('Never do this')
}
}
缺点
type Person = {
name: string
}
type Animal = {
age: number
}
const f1 = (a: Person | Animal) => {
if (a instanceof Person) {
}
}
type Rect = {
height: number
width: number
}
type Circle = {
center: [number, number]
radius: number
}
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
}
const f1 = (a: Rect | Circle) => {
if (isRect(a)) {
a
} else if (isCircle(a)) {
a
} else {
a
}
}
T = A | B | C | D | ...
则称 T 为可辨别联合
一句话概括:同名、可辨别的简单类型的 key
type Circle = { kind: 'circle', name: 'Circle' }
type Square = { kind: 'square', name: 'Square' }
type Shape = Circle | Square
const f1 = (a: Shape) => {
if (a.kind === "circle") {
a
} else {
a
}
}