4 min read
•Question 26 of 48mediumWhat is the never type in TypeScript?
Type for values that never occur.
What You'll Learn
- What never means
- Use cases
- never vs void
What is never?
never represents values that never occur. Used for functions that never return or exhaustive checks.
Functions That Never Return
code.tsTypeScript
// Throws an error
function fail(message: string): never {
throw new Error(message);
}
// Infinite loop
function infinite(): never {
while (true) {
// ...
}
}Exhaustive Checks
code.tsTypeScript
type Status = "pending" | "approved" | "rejected";
function handleStatus(status: Status): string {
switch (status) {
case "pending":
return "Waiting...";
case "approved":
return "Approved!";
case "rejected":
return "Rejected!";
default:
// If all cases handled, status is never
const _exhaustive: never = status;
return _exhaustive;
}
}
// If you add a new status, TypeScript will error!never vs void
code.tsTypeScript
// void: function returns but with no value
function logMessage(msg: string): void {
console.log(msg);
}
// never: function never returns
function throwError(msg: string): never {
throw new Error(msg);
}