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

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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.

 

In somecases, never type can be useful as well.

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.

以上是关于[TypeScript] Use TypeScript’s never Type for Exhaustiveness Checking的主要内容,如果未能解决你的问题,请参考以下文章

TypeScript基础教程

TypeScript基础教程

TypeScript基础教程

typescript入门第一课

Sequelize-typescript 'HasManyCreateAssociationMixin' 不是函数

前端开发React+TypeScript 项目初体验