The `assert-never` package provides a lightweight helper function designed for TypeScript's exhaustive checks on discriminated unions. Its primary purpose is to ensure that all possible cases of a union type are handled within a conditional block, leveraging the TypeScript compiler to catch unhandled cases at compile time. At runtime, if an unhandled case is encountered, `assertNever` will throw an `Error` by default, indicating a logical flaw. Alternatively, it can be configured to fail silently. The current stable version is 1.4.0. As a focused utility for a core TypeScript pattern, its release cadence is typically infrequent, with updates primarily for compatibility or minor feature enhancements rather than rapid iteration. Its key differentiator is its simplicity and direct application for a common TypeScript development pattern, making union type handling more robust.
npm install assert-neverVerified import paths — ran on the pinned version, not inferred.
This example demonstrates how `assertNever` is used within a TypeScript switch statement to ensure exhaustive handling of a discriminated union `Shape`. If a new type is added to `Shape` but not handled in `getArea`, TypeScript will raise a compile-time error at the `assertNever` call. At runtime, if an unhandled type reaches this point, `assertNever` will throw an error.
To prevent runtime errors, ensure all union cases are handled, or explicitly opt for silent failure with `assertNever(value, true)`.
Enable `strict: true` in your `tsconfig.json` or individually enable `strictNullChecks`, `noImplicitReturns`, and `noFallthroughCasesInSwitch`.
Add additional `if` or `case` statements to handle all remaining types in your discriminated union before the call to `assertNever`.
Review the logic preceding `assertNever` to ensure all possible runtime values are handled. If the type is correct but needs to be ignored at runtime, consider `assertNever(value, true)`.
No dependency data recorded yet.