WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

TypeScript · Basic · question 18 of 100

What is ’never’ type in TypeScript and what is its purpose?

📕 Buy this interview preparation book: 100 TypeScript questions & answers — PDF + EPUB for $5

The ‘never‘ type in TypeScript represents a value that should never happen. This type is primarily used in situations where the code should never reach this point, such as during exhaustive checks, unreachable endpoints, or infinite loops.

The purpose of the ‘never‘ type is to ensure type safety in situations where a value should not exist or should not be accessible. When a function or a variable is expected to have a ‘never‘ type, it indicates to TypeScript that the code should not reach this point, and therefore, it should issue a compile-time error if the code tries to access this value.

Here are some examples of ‘never‘ type usage:

1. Functions that throw errors:

function error(message: string): never {
    throw new Error(message);
}

In this case, the ‘error‘ function takes a string as an argument and throws an error. The function is expected to return a ‘never‘ type, which means it should not have a return value.

2. Functions with infinite loops:

function infiniteLoop(): never {
    while (true) {
    }
}

In this case, the ‘infiniteLoop‘ function contains an infinite loop that never terminates. The function is expected to return a ‘never‘ type, which means it should not have a return value.

3. Exhaustive type checking:

type UnionType = 'typeA' | 'typeB';

function exhaustiveCheck(value: UnionType): never {
    throw new Error(`Unhandled value: ${value}`);
}

function handleUnionType(value: UnionType) {
    switch (value) {
        case 'typeA':
            return 'Handled type A';
        case 'typeB':
            return 'Handled type B';
        default:
            return exhaustiveCheck(value);
    }
}

In this case, the ‘UnionType‘ is a union of different string literals, and the ‘handleUnionType‘ function handles each possible value of the ‘UnionType‘. If any unhandled value is passed to the function, it calls the ‘exhaustiveCheck‘ function, which is expected to return a ‘never‘ type, ensuring that the TypeScript compiler will raise an error if there is any unhandled value.

Using the ‘never‘ type allows TypeScript to identify unreachable code segments, improper type handling, or potential issues in the code, thus improving the overall type safety of the codebase.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic TypeScript interview — then scores it.
📞 Practice TypeScript — free 15 min
📕 Buy this interview preparation book: 100 TypeScript questions & answers — PDF + EPUB for $5

All 100 TypeScript questions · All topics