The never Type in TypeScript

never is a data type of values that will never happen. We use never in a function that will never reach the end of that function or when narrowing a type that will never return any data type. never can be assigned to any type available in TypeScript. It is also considered a subtype of all the types in TypeScript.

Examples

A function where never is implicitly dervied

function genericError() {
    return new Error("Oops! Something is wrong");
}

A function where it will never reach the end of that function, hence never is the return type

function someError(errorMessage: string): never {
    throw new Error(errorMessage);

    //Some more logic
}

Having never as an implicit return type through type narrowing

function determineType(param: number | T[]) {

    if (typeof param === 'number') {
        return param;
    }else if(Array.isArray(param)) {
        return param;
    }
}

In the function if the value of param is neither of type number or an array of type any, the type by default will be of type never.

Difference between never and void

The difference between never and void is that void can have as values null or undefined, but never is not allowed to have a value.

let a: void = null;
let b: never = null; //Type 'null' is not assignable to type 'never'.

This blog post was originally published on my blog Communicode, where I write about different tech topics.

TypeScript
Avatar for Muhammad Asfour

Written by Muhammad Asfour

I am a Full Stack Developer with over 5 years of experience. I have worked with different tech stacks such as: Groovy/Java, PHP, .NET/.NET Core (C#), Node.js, React, Angular, and Vue.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.