Convert Figma logo to code with AI

millsp logots-toolbelt

👷 TypeScript's largest type utility library

6,715
148
6,715
70

Top Related Projects

Collection of utility types, complementing TypeScript built-in mapped types and aliases (think "lodash" for static types).

10,793

Functional programming in TypeScript

Quick Overview

TS Toolbelt is a comprehensive TypeScript type library that provides a collection of utility types and advanced type operations. It aims to enhance TypeScript's type system by offering powerful tools for type manipulation, enabling developers to write more expressive and type-safe code.

Pros

  • Extensive collection of utility types covering a wide range of use cases
  • Improves type safety and reduces the need for type assertions
  • Well-documented with detailed explanations and examples
  • Actively maintained and regularly updated

Cons

  • Can increase compilation time due to complex type operations
  • Steep learning curve for some advanced type manipulations
  • May lead to overly complex type definitions if overused
  • Some utilities might become obsolete as TypeScript evolves

Code Examples

  1. Using the Union type to create a union of object properties:
import { Union } from 'ts-toolbelt'

type User = {
  id: number
  name: string
  email: string
}

type UserKeys = Union.Keys<User> // 'id' | 'name' | 'email'
  1. Applying the Readonly type recursively to create a deeply immutable object:
import { Object } from 'ts-toolbelt'

type DeepReadonly<T> = Object.Readonly<T, 'deep'>

type MutableUser = {
  id: number
  name: string
  settings: {
    theme: string
    notifications: boolean
  }
}

type ImmutableUser = DeepReadonly<MutableUser>
// All properties and nested properties are readonly
  1. Using the Merge type to combine multiple object types:
import { Object } from 'ts-toolbelt'

type UserBase = {
  id: number
  name: string
}

type UserContact = {
  email: string
  phone: string
}

type UserPreferences = {
  theme: 'light' | 'dark'
  notifications: boolean
}

type FullUser = Object.Merge<UserBase, UserContact, UserPreferences>
// Combines all properties from the three types

Getting Started

To use TS Toolbelt in your TypeScript project, follow these steps:

  1. Install the package:

    npm install ts-toolbelt
    
  2. Import the desired utility types in your TypeScript files:

    import { Union, Object } from 'ts-toolbelt'
    
  3. Use the imported types in your type definitions:

    type MyType = Union.Merge<TypeA, TypeB>
    type DeepReadonlyObj = Object.Readonly<MyObject, 'deep'>
    

Remember to check the official documentation for detailed information on available utilities and their usage.

Competitor Comparisons

Collection of utility types, complementing TypeScript built-in mapped types and aliases (think "lodash" for static types).

Pros of utility-types

  • Simpler and more focused library, easier to understand and use for beginners
  • Includes some unique utility types not found in ts-toolbelt
  • Lighter weight with fewer dependencies

Cons of utility-types

  • Less comprehensive set of utility types compared to ts-toolbelt
  • Not as actively maintained, with fewer updates and contributions
  • Limited documentation and examples compared to ts-toolbelt's extensive docs

Code Comparison

utility-types:

type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
type Merge<M, N> = Omit<M, Extract<keyof M, keyof N>> & N;

ts-toolbelt:

type Omit<O extends object, K extends Key> = Pick<O, Exclude<keyof O, K>>
type Merge<O1 extends object, O2 extends object> = O1 & Omit<O2, keyof O1>

Both libraries provide similar utility types, but ts-toolbelt often offers more advanced and flexible implementations. The code comparison shows the Omit and Merge types from both libraries, which are functionally similar but may have slight differences in implementation or constraints.

utility-types is a good choice for simpler projects or developers new to TypeScript utility types, while ts-toolbelt offers a more comprehensive and powerful set of tools for advanced TypeScript users and complex projects.

10,793

Functional programming in TypeScript

Pros of fp-ts

  • Focuses on functional programming concepts and patterns
  • Provides a comprehensive set of functional data types and utilities
  • Offers better integration with other functional programming libraries

Cons of fp-ts

  • Steeper learning curve for developers unfamiliar with functional programming
  • May be overkill for projects not heavily utilizing functional programming paradigms
  • Less focused on general-purpose TypeScript utility types

Code Comparison

fp-ts example:

import { pipe } from 'fp-ts/function'
import { map } from 'fp-ts/Array'

const double = (n: number) => n * 2
const result = pipe([1, 2, 3], map(double))

ts-toolbelt example:

import { A, N } from 'ts-toolbelt'

type DoubleArray = A.Map<[1, 2, 3], N.Multiply<2>>
// DoubleArray = [2, 4, 6]

Summary

fp-ts is ideal for projects embracing functional programming in TypeScript, offering a rich set of FP utilities and patterns. ts-toolbelt, on the other hand, provides a broader range of TypeScript utility types and is more suitable for general-purpose type manipulation. The choice between the two depends on the project's specific needs and the team's familiarity with functional programming concepts.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

banner

TypeScript's largest utility library

Language grade: JavaScript

📖 Documentation · 📣 Announcements · 🐞 Report Bug · 🍩 Request Feature · 🤔 Ask Questions

About

ts-toolbelt is the largest, and most tested type library available right now, featuring +200 utilities. Our type collection packages some of the most advanced mapped types, conditional types, and recursive types on the market.

Spend less time, build stronger. Benefit from a wide range of generic type functions to achieve better type safety.

We work just like lodash, or ramda, but applied to the type system. Our mission is to provide you with simple ways to compute, change, and create types. We abstract all those complex type checks away for you. We provide a simple, reusable, and standard API to help you get more done with TypeScript.

ts-toolbelt is a well organized package that can help you perform advanced operations on object types, union types, as well as function, and literal types. It is carefully and coherently designed for building robust, flexible, and type-safe software.

demo

We are a community and a knowledge base. Everyone is welcome to ask questions about types. If you are stuck or you misunderstand something, you came to the right place!. We welcome beginners and advanced developers to come take part. Welcome!

Getting Started

Prerequisites

npm install typescript@^4.1.0 --save-dev

For best results, add this to your tsconfig.json

{
  "compilerOptions": {
    // highly recommended (required by few utilities)
    "strictNullChecks": true,

    // this is optional, but enable whenever possible
    "strict": true,

    // this is the lowest supported standard library
    "lib": ["es2015"],
  }
}

Installation

npm install ts-toolbelt --save

Hello World

import {Object} from "ts-toolbelt"
// Check the docs below for more

// Merge two `object` together
type merge = Object.Merge<{name: string}, {age?: number}>
// {name: string, age?: number}

// Make a field of an `object` optional
type optional = Object.Optional<{id: number, name: string}, "name">
// {id: number, name?: string}

You can level-up, and re-code this library from scratch.

Documentation ⤢

Imports

The project is organized around TypeScript's main concepts:

AnyBooleanClassFunctionIterationList
NumberObjectObject.PStringUnionTest

TIP How to choose categories? Match your type with them.

There are many ways to import the types into your project:

  • Explicit

    import {Any, Boolean, Class, Function, Iteration, List, Number, Object, String, Union} from "ts-toolbelt"
    
  • Compact

    import {A, B, C, F, I, L, N, O, S, U} from "ts-toolbelt"
    
  • Portable

    import tb from "ts-toolbelt"
    

You can also import our non-official API from the community:

import {Community} from "ts-toolbelt"

TIP The community API is for our community to publish useful types that don't see fit in the standard API.

Utility Index

ANYOBJECTLISTFUNCTIONSTRINGUNIONCLASSBOOLEANNUMBEROBJECT.PITERATION
AwaitAssignAppendAutoPathAtDiffClassAndAbsoluteMergeIteration
AtAtLeastAssignComposeJoinExcludeInstanceNotAddOmitIterationOf
CastCompulsoryAtLeastCurryLengthFilterParametersOrGreaterPickKey
ComputeCompulsoryKeysCompulsoryExactReplaceHasXorGreaterEqReadonlyNext
ContainsDiffCompulsoryKeysFunctionSplitIntersectOfIsNegativeUpdatePos
EqualsEitherConcatLengthLastIsPositiveRecordPrev
ExtendsExcludeDiffNarrowMergeIsZero
KeyExcludeKeysDropNoInferNonNullableLower
KeysFilterEitherParametersNullableLowerEq
KnownKeysFilterKeysExcludePipePopNegate
IsHasExcludeKeysPromisifyReplaceRange
PromiseHasPathExtractReturnSelectSub
TryIncludesFilterUnCurryStrict
TypeIntersectFilterKeysValidPathListOf
xIntersectKeysFlatten
InvertGroup
ListOfHas
MergeHasPath
MergeAllHead
ModifyIncludes
NonNullableIntersect
NonNullableKeysIntersectKeys
NullableKeySet
NullableKeysLast
ObjectLastKey
OmitLength
OptionalList
OptionalKeysLongest
OverwriteMerge
PartialMergeAll
PatchModify
PatchAllNonNullable
PathNonNullableKeys
PathsNullable
PickNullableKeys
ReadonlyObjectOf
ReadonlyKeysOmit
RecordOptional
ReplaceOptionalKeys
RequiredOverwrite
RequiredKeysPartial
SelectPatch
SelectKeysPatchAll
UndefinablePath
UndefinableKeysPaths
UnionizePick
UnionOfPop
UpdatePrepend
WritableReadonly
WritableKeysReadonlyKeys
Remove
Repeat
Replace
Required
RequiredKeys
Reverse
Select
SelectKeys
Shortest
Tail
Take
Undefinable
UndefinableKeys
Unionize
UnionOf
UnNest
Update
Writable
WritableKeys
Zip
ZipObj

Archives ⤢

EXAMPLE https://millsp.github.io/ts-toolbelt/4.2.1/

Good to Know ⤢

In this wiki, you will find some extra resources for your learning, and understanding.

Are you missing something? Participate to the open-wiki by posting your questions.

Running tests

For this project

To run the lint & type tests, simply run:

npm test

For your project

Want to test your own types? Let's get started:

import {Number, Test} from "ts-toolbelt"

const {checks, check} = Test

checks([
    check<Number.Add<1, 30>, 31, Test.Pass>(),
    check<Number.Add<5, -3>, 2,  Test.Pass>(),
])

TIP Place it in a file that won't be executed, it's just for TypeScript to test types.

Continuous Integration

The releases are done with Travis CI in stages & whenever a branch or PR is pushed:

  • Tests are run with npm test
  • Tests against DefinitelyTyped
  • Releases to npm@[branch-name]

Compatibility

The project is maintained to adapt to the constant changes of TypeScript:

ts-toolbelttypescript
9.x.x^4.1.x

Major version numbers will upgrade whenever TypeScript had breaking changes.

Otherwise, the release versions will naturally follow the semantic versioning.

What's next

  • Automated performance tests

    # performance is checked manually with 
    npx tsc --noEmit --extendedDiagnostics
    
  • Need to write more examples

Related Projects

NameIntro
eledoc🌒 A material dark theme for TypeDoc.
material-candy🍬 A vscode theme to uplift your mood, stay happy and focused.
utility-typesCollection of utility types, complementing TypeScript built-in mapped types and aliases.

License

FOSSA
Status

NPM DownloadsLast 30 Days