How Does The TypeScript Never Type Work?
TypeScript is a programming language that offers many advantages compared to conventional JavaScript. Its most important advantage is the addition of typings. One of the typings added by TypeScript is the never type.
This article will explain, in detail, the never type and show when to use it, how to use it, and answer common questions.
Let's get to it 😎.
What is the TypeScript never type?
The never type indicates to the TypeScript compiler that the type contains no value.
You cannot assign any value to a type with a never type.
In simple words, the never type is for things that will never happen.
typescriptconst throwError = (error: string): never => {
throw new Error(error);
}
In this example, we use the never type to represent that the function called throwError will never return anything.
When to use the never type?
Although the never type is rarely used in TypeScript, there are still some valid use cases for this type.
Typically, the never type is used to impose restrictions on the return type of a function.
Here are the use cases for the never type:
1. To indicate that a function always throws.
typescriptfunction fail (): never {
throw new Error('error');
}
2. To indicate that a function never returns.
typescriptconst talk = (): never => {
while (true) {
console.log("Hello");
}
};
Read: The while loop in TypeScript
This function never stops executing, and its execution will result in an infinite loop.
Difference between never, any, void, unknown
Some developers confuse the never type with other TypeScript types. Here is a quick recap of the difference between the never type and other types.
The void type
The void type returns void, compared to the never type that never returns.
The any type
The any type represents a value of any type.
The unknown type
The unknown type also represents a value of any type.
The differences between any and unknown are:
- You cannot access the properties of an unknown variable.
- You cannot call or construct an unknown variable.
Final thoughts
As you can see, the never type is no rocket science.
And it does what its name sounds, indicating that a function never returns.
Even though you will rarely see this type, it is essential to understand it well to have a complete picture of the TypeScript language.
Here are other TypeScript tutorials for you to enjoy: