Day18: 【TypeScript 学起来】Narrowing Part 2

好 继续来笔记 Narrowing, 还有哪些方法能进行 narrow 型别呢。 若有错误,欢迎留言指教,感恩的心。


使用 type predicates(型别谓语)

  • 如果我们要自定义type guard,可以定义一个函式,这个函式返回的值就是 type predicates。
  • type predicate 指的就是 parameterName is Type。以下方例子, pet is Fish 就是 type predicate。
  • parameterName 必须要是函式中参数的名称,下方例子的的参数名称就是 pet , 所以 parameterName 就会是 pet
  • 函式最後会回传 true 或 false,如果是 true,表示符合该变数符合该 type predicate。
type Fish = { swim: () => void };
type Bird = { fly: () => void };

//pet 有可能是 Fish or Bird 的型别
//isFish 这个function 回传值的型别为 : pet is Fish,看是回传 true or false
//当返回了true, 那他就是Fish

function isFish(pet: Fish | Bird): pet is Fish { 
  return (pet as Fish).swim !== undefined;   //(pet as Fish)断言 pet 为 Fish 型别 , 所以 swim 不会是undefined 
}

Discriminated unions (可辨识联合)

TypeScript 可以针对相同的可识别的属性来自动判断型别,再去执行不同情境的操作,他有3个要素:

  1. 每个interface需要有相同的可辨识的属性,如 kind
  2. 使用type alias宣告联合型别,他包含了哪些型别, 如 type Shape = Circle | Square;
  3. 使用 type guard, 如shape.kind === "circle"

interface Circle {
  kind: "circle";
  radius: number;
}
 
interface Square {
  kind: "square";
  sideLength: number;
}
 
type Shape = Circle | Square;

function getArea(shape: Shape) {
  if (shape.kind === "circle") {
    return Math.PI * shape.radius ** 2;
  }
}

let area = getArea({ kind: "circle", radius: 5});
console.log(area);

可用在後端回传 response

看 pj 大大的文章是推荐在接收後端传来的 response 的时候很好用, status 是 OK 的话,则资料会带有 payload,否则资料会带有 error。我们可以自行定义多个不同的 Type,这些Type有共同的栏位, 如 status,那就用这个栏位来判断还有哪些属性。

最後没有判断到的情况可以利用 exhaustiveness checking, 用never型别表示不应该存在的状态,一般用於错误处理。

interface ISuccessResp {
  status: 'OK';  //相同栏位 status
  payload: unknown;
}

interface IErrorResp {
  status: 'ERROR';
  errorCode: number;
  description: string;
}

type Resp = ISuccessResp | IErrorResp;

const parseResponse = (resp: Resp) => {
  switch (resp.status) {
    case 'OK':  //透过 narrow 知道是 ISuccessResp 型别
      return resp.payload; //则去使用ISuccessResp的属性payload
    case 'ERROR': // 透过 narrow 知道是 IErrorResp 型别
      return resp.description; //则去使用IErrorResp的属性payload
    default:
      const _exhaustiveCheck: never = resp; 
      return _exhaustiveCheck;
  }
};

这两天跑出去玩,帮好久不见的朋友庆生,久违的开心XD (好多好朋友都是10月生日, 生日快乐呀, 天秤宝宝们
不过回到家,看到文章库存一天一天用完,觉得好可怕 QQ,然後明天又是礼拜一了,一起加油!!


参考资料

https://pjchender.dev/typescript/ts-narrowing/#user-defined-type-guards
https://www.typescriptlang.org/docs/handbook/2/narrowing.html
https://ithelp.ithome.com.tw/articles/10222470
https://blog.csdn.net/weixin_34088583/article/details/92693893
https://zh.wikipedia.org/wiki/%E6%A0%87%E7%AD%BE%E8%81%94%E5%90%88


<<:  过了一年,我更能享受其中了 谢谢你们

>>:  事件查看练习(二)--如何研究一个警告事件

【从实作学习ASP.NET Core】Day08 | 後台 | 新增商品类别

今天来处理昨天建立的 Category 商品类别模型 假如说商店有机会扩大经营的话,那商品类别势必会...

[Day14]ISO 27001 标准:资源传达

今天一样是 ISO 硬硬的标准,第七节 资源 及 传达。 通常分切成【人力资源安全】及【文件化资讯】...

TailwindCSS 从零开始 - 让 Variants 成为伪类的强大神器

除了 Tailwind CSS - 设定自己想要的 TailwindCSS 样式 Variant ...

第42篇-学习 DNS Server - 2

今天学习进度还是 鸟哥的 Linux 私房菜 -- DNS Server /etc/nsswitch...

Day 06 Interrupts for controlling peripherals

Utilize Mbed API to implement interrupts Purpose o...