ts笔记-辨析联合类型

如果一个类型是多个类型的联合类型,且多个类型含有一个公共属性,那么就可以利用这个公共属性,来创建不同的类型保护区块。这个公共属性称为辨识属性,这种类型称为辨析联合类型。

// 示例
interface Square {
  kind: 'square';
  size: number;
}

interface Rectangle {
  kind: 'rectangle';
  width: number;
  height: number;
}

type Shape = Square | Rectangle;

求面积

function area(s: Shape) {
  switch (s.kind) {
    case 'square':
      return s.size * s.size;
    case 'rectangle':
      return s.width * s.height;
  }
}

area用于求面积,但是如果联合类型添加了其他类型,area函数没有定义成处理这种类型的方法,就会导致bug参数。

interface Square {
  kind: 'square';
  size: number;
}

interface Rectangle {
  kind: 'rectangle';
  width: number;  
  height: number;
}

interface Circle {
  kind: 'circle';
  radius: number;
}


type Shape = Square | Rectangle | Circle;

function area(s: Shape) {
  switch (s.kind) {
    case 'square':
      return s.size * s.size;
    case 'rectangle':
      return s.width * s.height;
  }
}

// 编译通过,有隐藏的bug
area({
  kind: 'circle',
  radius: 1
})

为了避免这种潜在bug的出现,我们可以定义一个default情况

// 当Shape增加了新类型,但是area函数没有处理这种类型,编译直接报错
// 比如新增了Circle类型,不能将类型“Circle”分配给类型“never”
function area(s: Shape) {
  switch (s.kind) {
    case 'square':
      return s.size * s.size;
    case 'rectangle':
      return s.width * s.height;
    default:
      const invalidKind: never = s
      throw new Error(`Unknown ${invalidKind}`)
  }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章