联合类型
有时可能出现一个变量需支持多种类型的情况
1 2 3 4 5 6 7 8 9 10
| let phone:number|string phone = 13000000000 phone = "130-0000-0000" phone = false
const fn = function(type:number|boolean):boolean { return !!type }
|
交叉类型
有时可能出现需要将两个类型(接口)合并的情况
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| interface People { name:string, age:number }
interface Place { address:string }
const live = (man:People&Place):void=> { console.log(man) }
live({ name:"yajue", age:24, address:"下北泽" })
|
类型断言
告诉TS某个变量一定是某个类型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| let fn = (str:number|string):void=> { console.log((str as string).length) }
fn("12345") fn(67890)
interface A { foo:string } interface B { bar:string }
let fn2 = (foobar:A|B):void=> { console.log((foobar as A).foo) }
fn2({foo:"yajue"}) fn2({bar:"yjsp"})
|
类型断言常用在使用服务器环境全局变量的场景中
1 2 3 4
| window.abc = 123
(window as any).abc = 123
|
类型断言只能欺骗TS编译器,并不会真的去转换类型
1 2 3 4 5 6
| const fn = (type:any):boolean=> { return type as boolean }
console.log(fn(1)) console.log(fn("yajue"))
|
也可以使用as const对字面量进行断言,它与用const定义常量是有区别的
1 2 3 4 5 6 7 8 9 10 11 12
| let name1 = "nyn" as const const name2 = "yajue"
name1 = "mouse" name2 = "yjsp"
let a1 = [10, 20] as const const a2 = [10, 20] a1.unshift(30) a2.unshift(30)
|