TypeScript Variable Type: never

Definition of never

neverOther types (including nulland undefined) sub-type, from the representative value does not occur.

There are usually two manifestations of never:

  • Throw an exception
    // 返回值为 never 的函数可以是抛出异常的情况
    function error(message: string): never {
          
          
        throw new Error(message);
    }
    
  • Cannot execute to the end point
    // 返回值为 never 的函数可以是无法被执行到的终止点的情况
    function loop(): never {
          
          
        while (true) {
          
          }
    }
    

Features of never

  • never Variables of type can be assigned to variables of any type;
    let num: number;
    
    num = (() => {
          
          
        throw new Error('exception');
    })();
    
  • neverTypes of variables can only be neverthe type of assignment variables.
    let invalid1: never;
    let invalid2: never;
    
    invalid1 = "Hello World!"; // error, string 类型不能转为 never 类型
    invalid2 = (() => {
          
          
        throw new Error('exception');
    })();
    

Guess you like

Origin blog.csdn.net/qq_37164975/article/details/106132580