What is ts-toolbelt?
The ts-toolbelt package provides a comprehensive set of type utilities to improve TypeScript typing and enable type transformations, checks, and more complex operations. It enhances TypeScript's static typing capabilities and helps in building more robust type-safe applications.
What are ts-toolbelt's main functionalities?
Object Manipulation
Merge two types into one. This is useful for combining properties from multiple objects into a single type.
{ type Merged = Merge<{name: string}, {age: number}>; // Result: {name: string, age: number} }
Type Checking
Check if two types are equivalent. This utility helps in validating type structures for consistency.
{ type check = Equals<{a: string}, {a: string, b: number}>; // Result: false }
Conditional Types
Apply conditional logic to types. This feature allows for conditional type assignments based on certain conditions.
{ type Conditional = If<true, 'Yes', 'No'>; // Result: 'Yes' }
Other packages similar to ts-toolbelt
utility-types
Provides a collection of utility types for TypeScript, similar to ts-toolbelt. While utility-types focuses more on transformations and mappings, ts-toolbelt offers a broader range of type operations including type checks and advanced manipulations.
type-fest
A package that includes a variety of utility types for TypeScript. Type-fest is similar to ts-toolbelt but tends to be simpler and more focused on everyday use cases, whereas ts-toolbelt provides more comprehensive and complex utilities for advanced type manipulation.
Installation
npm install ts-toolbelt --save
yarn add ts-toolbelt
import * as T from 'ts-toolbelt'
type test0 = T.N.Minus<'5', '20'>
type O = {
a: {
b: {
c: 'hello'
d: 'goodbye'
}
}
}
type test1 = T.O.P.Update<O, ['a', 'b', 'c' | 'd'], [1, 2, 3]>
type test2 = T.O.Merge<O, {x: 'hello'}>
And so much more... But before you start reading the docs:
The library is organized around TypeScript concepts:
- T.A: Any types
- T.B: Boolean types
- T.C: Class types
- T.F: Funtion types
- T.I: Iteration types
- T.N: Number types
- T.O: Object types
- T.S: String types
- T.T: Tuple types
- T.U: Union types
type test3 = T.A.Is<'hello', string>
type test4 = T.T.Concat<[1, 2], [3, 4]>