交叉类型

交叉类型就是将多个类型合并为一个类型,这让我们可以把现有的多种类型叠加到一起成为一种类型,他包含了所需的所有类型的特性
交叉类型取所有类型的并集

  1. interface Person {
  2. name: string
  3. age: number
  4. }
  5. interface Animal {
  6. name: string
  7. color: string
  8. }
  9. const x: Person & Animal = {
  10. name: 'x',
  11. age: 1,
  12. color: 'red
  13. }

联合类型

在ts中,你希望属性为多种类型之一,如字符串或者数组 它使用 | 作为标记 如 string |number
联合类型表示多种类型的“或”关系

  1. function genLen(x: string | number) {
  2. return x.length
  3. }
  4. genLen('') // ok
  5. genLen([]) // error
  6. genLen(1) // ok

如果一个值是联合类型,我们只能访问此联合类型的所有类型里共有的成员

  1. interface Bird {
  2. name: string;
  3. age: number;
  4. }
  5. interface Fish {
  6. name: string;
  7. sex: string;
  8. }
  9. const user: Fish | Bird = { name:'zz',age:12,sex:'nan'};
  10. if(user.name) //ok 公共的不会报错
  11. if(user.age) //error 如果变量在运行时是Fish类型,那么调用就会出错

image.png

类型保护

  1. if((<Bird>user).age) //使用类型断言 确定是Bird类型

但是需要多次使用类型断言

用户自定义的类型保护

要定义一个类型保护,只要简单的定义一个函数,它的返回值是一个类型谓词