TypeScript细碎知识点:never 和 void 的区别

void

void类型表示没有任何类型。

  • 没有返回值的函数,其返回值类型为 void
    function warnUser(): void {
        console.log("This is my warning message");
    }
  • 声明为 void 类型的变量,只能赋予 undefined 和 null
    let unsable: void = undefined

never

never 类型表示永远不会有值的一种类型。

  • never类型是那些总是会抛出异常或根本就不会有返回值的函数表达式或箭头函数表达式的返回值类型
    // 返回never的函数必须存在无法达到的终点
    // 因为总是抛出异常,所以 error 将不会有返回值
    function error(message: string): never {
        throw new Error(message);
    }
    // 因为存在死循环,所以 infiniteLoop 将不会有返回值
    function infiniteLoop(): never {
        while (true) {
        }
    }
  • 永远不可能存在的情况
    const foo = 123;
    if (foo !== 123) {
        const bar = foo;    // bar: never
    }

posted on 2024-04-10 15:32  梁飞宇  阅读(51)  评论(0)    收藏  举报