Typescript 中的never到底意味着什么

73 阅读1分钟

never设计初衷是用来表示什么

never represent/indicate this particular part shouldn't be reachable.

never 表示这部分代码块不可到达

As the return type of functions 作为函数返回值的类型

It represents the values that never return to its caller

表示这个值永远不会不会返回给调用者

function controlFlowGuard(value: number | string){
    if(typeof value === 'string'){
            return value;// ReturnType string
    }else if( typeof value === 'number'){
             return value;// ReturnType: number
    }else{
        return value;// ReturnType: never 
    }
}

use to pointing that it should never happen.

用来指出这永远不该发生

type NonNullable<T> = T extends null | undefined ? never : T;

It's often denoted as ⊥ and signals that a computation doesn't return a result to its caller.

return 后面的表达式不会被计算,值不会返回给它的调用者

nevervoid的不同之处

  • function that doesn't explicitly return a value implicitly returns the value undefined in JavaScript.

函数没有直接指明return关键字暗含着返回undefined

  • functions with a void return type don't return any value, but they are reachable. 返回类型是void时不会返回任何值,但这个语句是可到达的

  • A function with never as return type never returns. It doesn't return undefined, either. The function doesn't have a normal completion, which means it throws an error or never finishes running at all. 函数的返回类型是never时,说明函数没有正常执行完成,要么抛出异常要么从来没有执行完成

function doInfinite(): never {
    while (true) {}
}

nullundefined 的区别

CleanShot 2023-12-18 at 20.23.06@2x.png

  • null 表示对象不存在
  • undefined 表示值不存在