美文网首页
联合类型 |

联合类型 |

作者: RickyWu585 | 来源:发表于2022-11-09 17:39 被阅读0次
  • A | B并集的意思,既可以是A也可以是B,也可以是A和B的交集
type A = {
  name:string
}
type B = {
  age: number
}

type C = A | B

const a1:C = {
  age:18
}
const a2:C = {
  name:"frank"
}
const a3:C = {
  name:"frank",
  age:18
}
  • 但是当 type A = string | number 时就类型特性就不好用了,因此需要进行类型收窄
  1. typeof:缺点是只支持基本类型,不具体
type A = string | number

const fn = (a:A) => {
  if(typeof a === "number"){
    a.toFixed()
  }else{
    a.split()
  }
} 
  1. instanceof,缺点是不支持string,number等基本类型,不支持TS独有的类型
const fn = (a: Date | Date[]) =>{
  if(a instanceof Date){

  }else if(a instanceof Array){

  }
}
  1. in,缺点是只适用于部分对象
type Person = {
  name: string
}

type Animal = {
  action: string
}

const fn  = (a:Person | Animal) =>{
  if('name' in a){
    a.name
  }else if('action' in a){
    a.action
  }
}
  • 类型收窄通用方法
  1. 类型谓词 is,缺点是麻烦
type Rect = {
  height: number
  width: number
}

type Circle = {
  center: [number,number]
  radius: number
}

const fn = (a: Rect | Circle) => {
  if(isRect(a)){
     a.height
  }else {
    a.center
  }
}

// is这里是必须是普通函数
function isRect(x: Rect | Circle): x is Rect{
  return 'height' in x && 'width' in x
}

function isCircle(x: Rect | Circle): x is Circle{
  return 'center' in x && 'radius' in x
}
  1. 可辨别联合:加一个可辨别的字段,这个字段只能是基本类型,且可区分
type Circle = {
  kind: "Circle"
  center: [number,number]
}

type Square = {
  kind: "Squrae"
  sideLength: number
}

const fn = (a: string | number | Circle | Square) => {
  if(typeof a === "string"){

  }else if(typeof a === "number"){

  }else if(a.kind === "Circle"){

  }else if(a.kind === "Squrae"){

  }
}
  1. 强制断言as

相关文章

  • TypeScript06(类型断言 | 联合类型 | 交叉类型)

    联合类型 函数使用联合类型 交叉类型 多种类型的集合,联合对象将具有所联合类型的所有成员 类型断言 语法:值 as...

  • TS学习笔记(7)-联合类型

    联合类型 ========= 知识点 联合类型是指可以包含多种数据类型 不推荐使用 联合类型的定义方法 联合类型的...

  • TypeScript入门基础(联合类型、对象类型)

    联合类型联合类型(Union Types)表示取值可以为多种类型中的一种。 联合类型使用 | 分隔每个类型。 这里...

  • typescript入门-高级类型

    交叉类型 联合类型 联合类型表示一个值可以是几种类型之一 只能访问此联合类型的所有类型里共有的成员 类型区分 通过...

  • TS 联合类型和交叉类型

    联合类型 通过 | 将变量设置多种类型,赋值时可以根据设置的类型来赋值。举例说明: 联合基础类型 联合对象类型 可...

  • 联合类型 |

    A | B 是并集的意思,既可以是A也可以是B,也可以是A和B的交集 但是当 type A = string | ...

  • 高级TypeScript

    1、联合类型和类型保护 联合类型:一个变量可能有两种或两种以上的类型。 类型保护:联合类型的具体实例需...

  • typescript语法精讲一(笔记)

    - 使用联合类型 联合类型保证传入的是联合中的某一个类型的值即可 -可选类型补充 可选类型可以看作是 类型 和 u...

  • TypeScript中的约束与类型断言(2)

    一、TypeScript中的联合类型 联合类型表示取值可以为多种类型中的一种 只能访问此联合类型的所有类型里共有的...

  • flow中文文档(八)

    联合类型 不相交联合 精确的不相交联合 联合类型 有时,创建一个其他类型之一的类型很有用。例如,您可能希望编写一个...

网友评论

      本文标题:联合类型 |

      本文链接:https://www.haomeiwen.com/subject/vpyntdtx.html