One of the rarely used type in TypeScript is the never
type, which represents instances where value is unreachable.
In this article, we’ll discuss the never
type and how it is used in TypeScript.
What is never type?
The never
type is used when the return statement is unreachable.
It may sound confusing. But we often write code where the code block does not return anything.
function throwError() {
throw new Error("this will always throw an error");
// never reach to the return statement
return -1;
}
The above function will always throw an error and never reaches to return statement.
When the never type used?
As we discussed earlier, that never
type can be used when the return statement is unreachable.
function throwError() {
throw new Error("this will always throw an error");
return -1;
}
We wrote a function named throwError
, which will always throw an error according to its logic. And once the function throws an error, it will execute immediately, which means its return statement will never execute.
This is where never
type is used to prevent possible logical errors in code.
How to define the never type to the function?
function throwError(): never {
throw new Error("this will always throw an error");
}
If the function defined with the never
type it should not have a return statement, otherwise it will throw an error.
function throwError(): never {
throw new Error("this will always throw an error");
// ⛔️ Type -1 is not assignable to type 'never'
return -1;
}
As you can see if we define never
type to the function which returns value it throws an error “Type -1 is not assignable to type ‘never’”.
We have another type void
in TypeScript, which is used when a function does not have a return statement. So, why not use void
then?
What is the difference between void and never?
The void
type is used for a function that does not return anything, but technically it can return null
or undefined
.
function logger(): void {
console.log("Hello world");
}
As we know, the never
cannot reach the return statement; in fact, it does not execute completely.
function throwError(): never {
throw new Error("this will always throw an error");
}
When the never type not used?
When the function’s return statement is unreachable only for some specific cases, we should not annotate it with never type. For example, if we throw an error for only some cases, the function should not be annotated with never.
function validateNumber(num: number): number {
if (!num) {
throw new Error('input is required!');
}
return num;
}
We annotated the function as number
not never
because it returns a number in some cases.
Conclusion
We only define never for those functions where the return statement is unreachable. And if there is only a possibility of potential error, we should not annotate it with never
.
Learn More: