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

Posted Answer1215

tags:

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

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的主要内容,如果未能解决你的问题,请参考以下文章

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

[TypeScript] Catch unsafe use of "this" in TypeScript functions

[Typescript] Dynamic types: Use TypeScript's Mapped Types and Template Literal Types Together(代码

[Typescript Kaop-ts] Use AOP in Vue Components with TypeScript and Kaop-ts

关于 Vue 3 + TypeScript 和 Augmenting-Types-for-Use-with-Plugins 的问题

[TypeScript] Installing TypeScript and Running the TypeScript Compiler (tsc)