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

[TypeScript] Use the never type to avoid code with dead ends using TypeScript

时间:2017-02-01 10:38:28      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:string   lock   another   void   nic   diff   div   rom   ret   

Example 1: A never stop while loop return a never type.

function run(): never {
   while(true){
      let foo = "bar";
   }
} 

 

Example 2: Never run If block

const foo = 123;

if(foo !== 123) {
 let bar: never = foo;
}

 

You can use this to do exhaustive checks in union types.

For example, let‘s say you have a variable returned from the server that can be a string or a number. You can easily add code that handles different cases using the JavaScript typeof operator. You can add an additional else, and assign the variable to a never to ensure that all types were eliminated.

declare var foo:
    | string
    | number;


if(typeof foo === "string") {
  /* todo */
} else if (typeof foo === "number"){
  /* todo */
} else {
  const check: never = foo;
}

 

Later, if you need to add another type to the union, for example, a Boolean, you will now get nice errors at all the places where the new type was not handled, because only a never is assignable to a never. Now, if you go ahead and add another typeof to handle this new case, the error goes away.

[TypeScript] Use the never type to avoid code with dead ends using TypeScript

标签:string   lock   another   void   nic   diff   div   rom   ret   

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

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