码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-11-10 00:21:09      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:size   called   miss   been   hand   str   als   sed   throw   

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

标签:size   called   miss   been   hand   str   als   sed   throw   

原文地址:http://www.cnblogs.com/Answer1215/p/7811540.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!