类型断言 联合类型 交叉类型

联合类型

1
2
let phone: number|string = 114514
phone = '114-514'

交叉类型

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
interface Student {
name:string
age:number,
score:number,
exam():number
}

interface Child {
happy:boolean
}

const analyseChildStudent = (cs:Child & Student):void => {
console.log(cs.age)
console.log(cs.score)
console.log(cs.happy)
}

analyseChildStudent({
name:'张三',
age:11,
score:59,
exam(): number {
return this.score++;
},
happy:false,
})

类型断言(慎用)

只能欺骗编译器通过编译,并不能让类型真的发生变化

1
2
3
4
5
6
const phoneLength = (phone:number | string):number => {
return (phone as string).length
}
const phoneLength = (phone:number | string):number => {
return (<string>phone).length
}