0%

【046】typescript:联合类型,交叉类型,类型断言

联合类型

联合类型使用 | 分隔每个类型,表示多种类型的联合。

  1. 变量使用联合类型
    比较常见的是电话号码,电话号码可以是手机号码,也可以是座机。其中手机号码是纯数字,座机是字符串,这个时候就可以使用联合类型了。

    1
    2
    3
    let phone: number | string = 13222222222
    // 或者
    let phone: number | string = '020-123456'
  2. 函数使用联合类型

    1
    2
    3
    4
    5
    6
    function savePhone(phone: number | string) {
    if (typeof phone === 'number') console.log('保存了手机号码')
    else if (typeof phone === 'string') console.log('保存了座机')
    }
    savePhone(13222222222) // 保存了手机号码
    savePhone('020-123456') // 保存了座机

交叉类型

交叉类型使用 & 分隔每个类型,是将多个类型合并为一个类型。

比如上一章接口说到的男人女人要怎么和人关联起来

1
2
3
4
5
6
7
8
9
10
11
12
13
14
interface Person {
name: string,
age: number
}
interface Sex {
sex: '男' | '女'
}
const sexFn = (info: Person & Sex) => {
console.log(info.name)
console.log(info.age)
console.log(info.sex)
}
sexFn({ name: '老王', age: 30, sex: '男' })
sexFn({ name: '翠花', age: 18, sex: '女' })

类型断言

类型断言Type Assertion可以收到指定一个类型,允许我们重写TypeScript数据的类型。

  1. 语法01:value as type

    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
    27
    28
    29
    interface Cat {
    run: () => void
    }
    interface Fish {
    swim: () => void
    }

    // 以下方法会报错,虽然猫和鱼都是动物,但是鱼并不会奔跑,在动物调用时时没有run这个方法的。
    // const isCat = (animal: Cat | Fish): boolean => {
    // if (typeof animal.run === 'function') return true
    // else return false
    // }

    // 所以应该在动物调用时给这个动物指定一个run的方法,如下:
    const isCat = (animal: Cat | Fish): boolean => {
    if (typeof (animal as Cat).run === 'function') return true
    else return false
    }

    const cat: Cat = {
    run() {}
    }
    console.log(isCat(cat)) // true

    const fish: Fish = {
    swim() {}
    }
    console.log(isCat(fish)) // false

  2. 语法02:<type>value

    1
    2
    3
    4
    const isCat = (animal: Cat | Fish): boolean => {
    if (typeof (<Cat>animal).run === 'function') return true
    else return false
    }

as const

const 声明的变量如果是基本类型,那么不允许改变,如果是引用类型,那么只要不改变引用的地址就是可以的。
举个例:

1
2
3
4
const a = 1
a = 2 // 报错
const b = [2, 3]
b.push(4) // 通过

那么如果使用as const断言会怎么样呢

1
2
3
4
5
let c = 5 as const
c = 6 // 报错

const d = [7, 8] as const
d.push(9) // 报错,因为此时变量d已经被断言字面量为[7, 8],数据无法再做任何修改

类型断言是不具影响力的

从下面的例子可以看出,虽然参数f通过了编译,但是并没有影响到最终的结果。因为在编译过程中,类型断言已经被删除了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// ts
function eFn(f: any): string {
return f as string
}

const g = eFn(true)
console.log(g) // true

// 编译成js后
function eFn(f) {
return f;
}
var g = eFn(true);
console.log(g); // true

注意

虽然使用类型断言可以指定一个类型,但是这样做只是避开了typeScript编译器的检测,在运行时还是有可能报错,所以在开发时应该避免滥用类型断言。