TypeScript Type Toolbelt

9.6.0 · active · verified Sun Apr 19

ts-toolbelt is a comprehensive collection of over 200 advanced type utilities for TypeScript, serving as a 'Lodash for types'. It enables complex type computations, transformations, and creations, abstracting away intricate conditional, mapped, and recursive type definitions. Currently at version 9.6.0, the library maintains an active development pace with releases tied to TypeScript's breaking changes, adhering to semantic versioning. Its key differentiators include an extensive suite of rigorously tested utilities, robust design for manipulating object, union, function, and literal types, and a commitment to providing a standardized API for enhancing type safety in large-scale TypeScript projects. It aims to improve type correctness and introduce new features to the TypeScript type system itself, trading compilation CPU/RAM for higher type safety.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates installation, recommended TypeScript compiler options, and basic usage of object, list, and union type utilities.

npm install ts-toolbelt --save-dev
# For best results, ensure tsconfig.json includes:
# {
#   "compilerOptions": {
#     "strictNullChecks": true,
#     "strict": true,
#     "lib": ["es2015"]
#   }
# }

import { O, L, U } from 'ts-toolbelt';

// 1. Merge two object types, handling optional properties gracefully
type User = { id: string; name?: string; };
type Address = { street: string; zip: number; };
type MergedUserAddress = O.Merge<User, Address>;
// Expected: { id: string; name?: string; street: string; zip: number; }

// 2. Append an element to a tuple type
type MyTuple = [1, 2];
type AppendedTuple = L.Append<MyTuple, 3>;
// Expected: [1, 2, 3]

// 3. Exclude types from a union
type EventStatus = 'pending' | 'success' | 'failed' | 'cancelled';
type ActiveStatus = U.Exclude<EventStatus, 'failed' | 'cancelled'>;
// Expected: 'pending' | 'success'

interface Config {
  theme: 'dark' | 'light';
  version: number;
  options?: { debug: boolean; };
}

// 4. Update a nested property (requires Object.Path and Object.Update)
import { Object } from 'ts-toolbelt';
type UpdatedConfig = Object.Update<Config, ['options', 'debug'], true>;
// Expected: { theme: 'dark' | 'light'; version: number; options?: { debug: true; }; }

view raw JSON →