联合类型
ts
type A1 = number
type B1 = string
type C1 = A1 | B1
const c1: C1 = 42
type A2 = { name: string }
type B2 = { age: number }
type C2 = A2 | B2
const c2: C2 = {
name: 'John',
age: 18
}
问题:如何使用和区分联合类型?
- 使用 typeof 区分,也叫类型收窄。
ts
const f1 = (a: number | string) => {
if(typeof a === 'number') {
a.toFixed(2)
} else if(typeof a === 'string') {
parseFloat(a).toFixed(2)
} else {
throw new Error('Never do this')
}
}
TS 中 typeof x 结果有多少种?string/number/bigint/symbol/null/undefined/object/function
- 使用 instanceof 区分,也叫类型收窄。
ts
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')
}
}
- 使用 in 来做收窄类型
ts
type Person = {
name: string
}
const f1 = (a: Person | Person[]) => {
if('name' in a) {
a // Person
} else {
a // Person[]
}
}
- 使用 JS 中判断类型的函数来区分
ts
const f1 = (a: string | string[]) => {
if(Array.isArray(a)) {
a.join('\n').toString()
} else if (typeof a === 'string') {
parseFloat(a).toFixed(2)
} else {
throw new Error('Never do this')
}
}
接上面的问题发问:有没有区分类型的完美方法?类型谓词(is),is 支持所有类型,缺点是麻烦。
问题: any 是所有类型的联合吗?为什么?