[TypeScript] Use TypeScript’s never Type for Exhaustiveness Checking

TypeScript 2.0 introduced a new primitive type called never, the type of values that never occur. It helps model the completion behavior of functions more accurately and can also be used for exhaustiveness checking.

 

never type means that 'That part of code cannot be reached'.

 

In somecases, never type can be useful as well.

复制代码
const enum ShirtSize {
  XS,
  S,
  M,
  L,
  XL
}

function assertNever(value: never): never {
  // throw Error(`Unexpected value '${value}'`)
  // Adjusted for plunker output
  console.log(Error(`Unexpected value '${value}'`));
}

function prettyPrint(size: ShirtSize) {
  switch (size) {
      case ShirtSize.S: console.log("small");
      case ShirtSize.M: return "medium";
      case ShirtSize.L: return "large";
      case ShirtSize.XL: return "extra large";
      // [ts] Argument of type 'ShirtSize.XS' is
      // not assignable to parameter of type 'never'.
      default: return assertNever(size);
  }
}

prettyPrint(ShirtSize.S)
prettyPrint(ShirtSize.XXL)
复制代码

In the example, we want to make sure that every time in the enum ShirtSzie has been handled by the 'prettyPrint' function.

But sometime, we might miss one case. That's where 'assertNever' function can help to make sure, we have gone though all the cases.

 

 

posted @   Zhentiw  阅读(321)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2017-09-14 [Vue + TS] Create your own Decorators in Vue with TypeScript
2017-09-14 [Vue + TS] Use Dependency Injection in Vue Using @Inject and @Provide Decorators with TypeScript
2017-09-14 [D3JS] Add more map layer and color
2017-09-14 [Javascript] Iterate Over Items with JavaScript's for-of Loop
2016-09-14 [Angular 2] More on *ngFor, @ContentChildren & QueryList<>
2016-09-14 [Angular 2] *ngFor
2016-09-14 [Angular 2] Directive intro and exportAs
点击右上角即可分享
微信分享提示