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) {
}
}