1、联合类型
let phone: number | string = '0831-25601'
// 1、最初:传入的是number,但是返回值要的是布尔类型
// let fn = function (type: number): boolean {
// 2、变动:现在传入的是boolean,依旧返回值要的是布尔类型
let fn = function (type: number | boolean): boolean {
return !!type // 强转!!
}
console.log(fn(0)); // false
console.log(fn(true)); // true
2、类型断言 as
不可滥用,避免运行时的错误
// 第一种写法
let fn = function (num: number | string): void {
// 用()包裹,使用as,左边是参数,右边是断言的类型
console.log((num as string).length)
}
fn('jjjj') //4
fn(789) // undefined (只能欺骗编译器,但无法避免运行时的错误)
// 第二种写法
interface A {
shape: string
}
interface B {
color: string
}
let fn1 = function (type: A | B): void {
// console.log(type.shape) // 报错 Property 'shape' does not exist on type 'B'
// 用()包裹,左边是<>,<>里面放断言类型
console.log((<A>type).shape) // 写法1
console.log((type as A).shape) // 写法2
}
fn1({ color: 'red' }) // undefined undefined (只能欺骗编译器,但无法避免运行时的错误)
// 用any类型做临时断言
(window as any).aaa=666
3、交叉类型
interface Pople {
name: string,
age: number
}
interface Woman {
sex: string
}
// 使用&连接,类似extends
const huangzi = (woman: Pople & Woman): void => {
console.log(woman)
}
huangzi({ name: '皇子', age: 18, sex: '女' }) // { name: '皇子', age: 18, sex: '女' }