๐ ๐ฎ๐๐๐ฒ๐ฟ๐ถ๐ป๐ด ๐ง๐๐ฝ๐ฒ๐ฆ๐ฐ๐ฟ๐ถ๐ฝ๐ ๐ป๐ฒ๐๐ฒ๐ฟ ๐ง๐๐ฝ๐ฒ
The never type is not an edge case. It is a tool for safety. You can use it to stop bugs before they reach production.
Here are three ways to use it.
- Exhaustive Checks
Imagine you have a union type for an API state. You use a switch statement to handle every state.
If a teammate adds a new state like "rate_limited", your function might return undefined. You will not get a compiler error. This creates a runtime bug.
The fix is a never assignment in your default case:
function renderState(state: ApiState) {
switch (state.status) {
case "idle":
return "Waiting...";
case "loading":
return "Loading...";
case "success":
return Data: ${state.data};
case "error":
return Error: ${state.message};
default:
const _exhaustive: never = state;
return _exhaustive;
}
}
Now, if someone adds a new state, TypeScript throws an error. It forces you to handle the new case. This keeps your code in sync with your types.
- Conditional Types
The never type is the identity element of unions. In a union, T | never equals T. TypeScript automatically removes never from the result.
This is how the Exclude utility works:
type MyExclude<T, U> = T extends U ? never : T;
When you filter a union, the members that match the criteria become never. TypeScript strips them out. This allows you to build precise utility types to filter events or functions.
- Mapped Types
You can use never to block specific keys in an object. This is useful for marking properties as deprecated or restricted.
type BlockedKeys = "password" | "token";
type SafeConfig
If your input has a "password" key, the output will set that key to never. This makes it impossible to use that property correctly.
Never vs Void vs Unknown
- void: The function returns undefined.
- never: The function never finishes. It throws an error or loops forever.
- unknown: The value can be anything.
- any: You turn off type checking. Avoid this.
Use never to build a safety net. Add a default case with a never assignment to your switch statements today. It prevents bugs when your types grow.