๐— ๐—ฎ๐˜€๐˜๐—ฒ๐—ฟ๐—ถ๐—ป๐—ด ๐—ง๐˜†๐—ฝ๐—ฒ๐—ฆ๐—ฐ๐—ฟ๐—ถ๐—ฝ๐˜ ๐—ป๐—ฒ๐˜ƒ๐—ฒ๐—ฟ ๐—ง๐˜†๐—ฝ๐—ฒ

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.

  1. 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.

  1. 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.

  1. 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 = { [K in keyof T]: K extends BlockedKeys ? never : T[K]; };

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

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.

Source: https://dev.to/kaithorne/mastering-typescripts-never-type-exhaustive-checks-conditional-types-and-real-patterns-4c26