类型断言 | 联合类型 | 交叉类型
联合类型
let phone: number | string
phone = 18888888888
phone = '+86-18888888888'
函数使用联合类型
function fn(v: number | boolean): boolean {
return !!v
}
交叉类型
多种类型的集合,联合对象将具有所联合类型的所有成员
interface People {
age: number,
height: number
}
interface Boy {
sex: string
}
const b = (b: People & Boy) => {
console.log(b.age)
console.log(b.height)
console.log(b.sex)
}
b({age: 18, height: 180, sex: 'boy'})
类型断言
语法:值as类型或<类型>值value as string <string>value
interface A {
run: string
}
interface B {
sing: string
}
function fn(v: A | B) {
return v.run // 这样写是有警告的应为B的接口上面是没有定义run这个属性的
}
interface A {
run: string
}
interface B {
sing: string
}
function fn(v: A | B) {
return (v as A).run // ok
}
需要注意的是,类型断言只能够「欺骗」TypeScript 编译器,无法避免运行时的错误,反而滥用类型断言可能会导致运行时错误
使用any临时断言
window.a = 'a' // error
(window as any).a = 'a'
as const
是对字面值的断言,与const直接定义常量是有区别的
const name = 'mk'
name = 'mankeung' // error
let name = 'mk' as const
name = 'mankeung' // error
let a = [1, 2] as const
const a2 = [3, 4]
a.unshift(5) // error
a2.unshift(5) // ok
类型断言是不具影响力的
function fn(v: any): boolean {
return v as boolean
}
fn(1) // 编译过程中会删除类型断言 返回1并不会变布尔值