Typescript Never explained

Last update: 2022-12-01
Quick Win's logo Quick Win
TypeScript TypeScript

In TypeScript, the never type represents the type of values that never occur. This is useful for describing the return type of functions that never return (e.g. because they throw an exception).

Here is an example of a function that has a return type of never:

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

In this example, the throwError function takes a string parameter and throws an error with the provided message. Since the function never returns a value, the return type is never.

You can work around the never type by using type guards. A type guard is a boolean expression that performs a runtime check that narrows the type of a value. You can use a type guard to narrow the type of a value from a union type that includes the never type to a more specific type.

For example:

function getValue(x: number | never): number {
	if (typeof x === 'number') {
		return x;
	throw new Error('Unexpected value');

In this example, the getValue function takes a value of type number | never and returns a value of type number. The type guard typeof x === 'number' checks that x is a number at runtime, and if the check passes, the function returns x as a value of type number. If the check fails, the function throws an error.

Simon Grimm