天天看點

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

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.

declare var foo:
    | string
    | number;


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

繼續閱讀