tsafe

raw JSON →
1.8.12 verified Mon Apr 27 auth: no javascript

A collection of utility functions and type helpers for TypeScript, currently at version 1.8.12. Released frequently (multiple releases in 2024). Provides runtime functions like assert and assertDeepEqual, along with type-level utilities such as Equals, EqualsT, ReturnType of, UnpackPromise, Assert, Id, etc. No runtime dependencies. Tree-shakable and supports Deno. Differentiates by offering TypeScript utility types that require runtime implementations (e.g., assertion functions), complementing the standard library.

error TypeError: tsafe_1.assert is not a function
cause Attempting to use CommonJS require with tsafe which is ESM-only
fix
Use ES module import syntax: import { assert } from 'tsafe';
error Module '"node_modules/tsafe/index"' has no exported member 'ReturnTypeOf'. Did you mean to use 'import ReturnTypeOf from "tsafe"'? (ts2305)
cause Case-sensitive export name 'ReturnTypeOf'
fix
Correct the import: import { ReturnTypeOf } from 'tsafe'; (capitalization matters)
error This expression is not callable. Type 'never' has no call signatures.
cause Using assert in a function with return type never incorrectly
fix
Ensure assert is called with a boolean expression that narrows correctly; consider using assert as a type guard with a custom message.
breaking Version 0.x to 1.x changed export structure; assert moved from 'tsafe/assert' to 'tsafe'.
fix Update imports to import from 'tsafe' directly.
deprecated The 'Equiv' type was deprecated in v1.5 in favor of 'Equals'.
fix Replace 'Equiv' with 'Equals'.
gotcha assert function throws on false, not just narrows type. Do not use for branching logic without try-catch.
fix Use user-defined type guards or if statements for branching.
breaking In v1.8.0, 'assertDeepEqual' was added; previous deep equality check required manual comparison.
fix Upgrade to use built-in deep equality.
npm install tsafe
yarn add tsafe
pnpm add tsafe

Shows importing and using assert, assertDeepEqual, and the Equals type helper in TypeScript.

import { assert, assertDeepEqual, type Equals } from 'tsafe';

// Type-level equality check (compile time)
type Check = Equals<{ a: string }, { a: string }>; // true

// Runtime assertion with type narrowing
function greet(input: unknown) {
  assert(typeof input === 'string', 'Expected string');
  console.log(input.toUpperCase()); // TypeScript knows input is string
}

// Deep equality check for objects
assertDeepEqual({ x: 1, y: 2 }, { y: 2, x: 1 }); // passes

// Exhaustive switch helper
function handleShape(s: 'circle' | 'square') {
  switch (s) {
    case 'circle': return 'round';
    case 'square': return 'corners';
    default: return assert(false, 'Unhandled shape'); // never reached
  }
}