TypeScript Never Type

Type Script Never Type

Never is primitive type, which represent value that will never occur. Never type introduced in TypeScript 2.0   

When to use Never

  • Function never return any value.
  • Variable with impossible
  • Function contain unreachable code block or

You can use the when your function never returns any value or function contain unreachable code block. 

  

       
    

Function never return any value.

  

        // due to infinite while loop this function will  never returns, its type is never
        function infiniteWhileLoop(): never {
        while (true) {
        console.log('Hello TypeScript');
        }

        }

        function throwErrorMessage(message :string): never {

        throw new Error(message)
        }
    

Variable with impossible type

  

        function neverWithDataType(value:   number|string) {
        if (typeof value === "string") {
        // Type string
        console.log(value);
        } else if (typeof value === "number") {
        // Type number
        console.log(value);

        } else {
        // Type never
        console.log(value);
        }
        }
    

The Difference Between never and void

You might ask yourself why TypeScript needs a never type when it already has a void type. Although the two might seem similar, they represent two different concepts:

  • A function that doesn't explicitly return a value implicitly returns the value undefined in JavaScript. Although we typically say that such a function "doesn't return anything", it returns. We usually ignore the return value in these cases. Such a function is inferred to have a void return type in TypeScript.
  • A function that has a never 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.

If you're interested in type theory, the never type is a bottom type, also known as a zero type or an empty type. It's often denoted as ⊥ and signals that a computation doesn't return a result to its caller. The void type, on the other hand, is a unit type (a type that allows only one value) with no defined operations.