Back to all questions

What is never in TypeScript?

Devs Hive

Devs Hive

Seen on interview: 3 users

Put simply, never means something that will never happen. You probably thought of the void type just now and wondered what the difference between them is?

If you look at these types from the perspective of functions, technically void still returns a value, because in JavaScript a function implicitly returns undefined even when there is no return. The never type, on the other hand, means that execution will never reach a return.

Let's dig deeper

A good real-world example of never is Nest.js and its wrappers around the Error object, which add a bit of sugar to error handling. The code inside these functions never reaches the return keyword, since they always end with an error.

// виконання коду в функціях, ніколи не дійде до return тому тип завжди буде never

throw new NotFoundException();
throw new ForbiddenException();
throw new UnauthorizedException();

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

Another example of never is a loop that never terminates. In the infiniteLoop function, code execution never reaches a return, so the type will also be never.

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

Seen on interview?

Comments (0)

Sign in to leave a comment

No comments yet. Be the first!