×
☰ See All Chapters

Typescript never

In TypeScript 2.0, a new primitive type called never was introduced. It represents the type of values that never occur. never is a subtype of and assignable to every type. No type is a subtype of or assignable to never (except never itself).

What are the never values, how to create never values?

If a variable is assigned with the return value of a function and function never returns a value. For example, if a function never returns or always throws an error, its return value is assigned to the never type. Similarly, if a variable is assigned in a block of code that will not be executed, its type is set to never.

let bar: never = (() => { throw new Error('Error!') })();

 

let returnVal = function functionWithNeverExecutingBlock(value: any) {

    if (typeof value === "string" && typeof value === "number") {

        value;  // Type never

    }

}

 

let neverReturnVal = function() {

    while (true) {

        console.log("Never return");

    }

};

 

let possibleNeverValue = function fucntionWithPossibleNeverBlock(value: string | number) {

    if (typeof value === "string") {

        value;  // Type string

    } else if (typeof value === "number") {

        value;  // Type number

    } else {

        value;  // Type never

    }

}

Typescript void

If a function doesn't return a value, the type of its return value is set to void. Variables can be declared with the void type, but they can only be given one of two values: undefined and null.

The Difference Between never and void

A function that returns nothing can have return type as void. However a function that never returns (or always throws) can have return type as never. void is something that can be assigned (without strictNullChecking) but never cannot  be assigned to anything other than never.


All Chapters
Author