How to Use of the never Keyword in TypeScript

Muhammad Ibrahim Alvi Feb 15, 2024
How to Use of the never Keyword in TypeScript

This tutorial provides a brief guideline about using the new Data Type in the TypeScript never keyword with the popular use cases being used among the developers.

Use of the never Keyword in TypeScript

The never keyword is a new type in TypeScript, which specifies the values that will never occur. The never type is utilized when the programmer is sure that something will not occur.

Now let’s consider that you write a function that will always throw an exception or never return to its endpoint.

Code Example:

function throwNewError(errorMsg: string): never {
            throw new Error(errorMsg);
}

function keepInfiniteProcessing(): never {
            while (true) {
         console.log('I always does something and never ends :).')
     }
}
console.log(throwNewError("Error occured"));

In the above coding example, the throwNewError() function will always throw an error when it is called, and on the other hand, the keepInfiniteProcessing() function will always keep executing and will never going to reach its endpoint because the while loop has a true condition which will never terminate the loop and it will never end. Therefore, the never type in TypeScript is used to specify the value that will never occur or return from a function.

Output:

while loop has a true condition which will always throw an error when it is called

The variables also acquire the type of never when narrowed by the guard of any type that can never be true. The variable type can be narrow with operators like in, typeof, instanceof.

We can narrow down the type for the variable for which we are sure that these will never occur in some places.

Code Example:

function formatFunction(valueData: string | number) {
    if (typeof valueData === 'string') {
        return valueData.trim();
    } else {
        return valueData.toFixed(2); // we're sure it's number
    }
    // not a string or number
    // "value" can't occur here, so it's type "never"
}

let response = formatFunction("Hello");
    console.log(response);

Output:

narrow down the type for the variable which in some places these never occur

Muhammad Ibrahim Alvi avatar Muhammad Ibrahim Alvi avatar

Ibrahim is a Full Stack developer working as a Software Engineer in a reputable international organization. He has work experience in technologies stack like MERN and Spring Boot. He is an enthusiastic JavaScript lover who loves to provide and share research-based solutions to problems. He loves problem-solving and loves to write solutions of those problems with implemented solutions.

LinkedIn

Related Article - TypeScript Keyword