typescript-conditional-types
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

typescript-conditional-types

npm version Conventional Commits code style: prettier

Helpers for typescript generic types

Table of Contents

Motivation

Creating complex types with conditional types ( T extends U ? X : Y ) could be a little verbose. This package aims to simplify code and make it more readable.

Instead of

type ComplexType<A> = A extends boolean
  ? number
  : A extends number ? number : string
  : string

You could write

type ComplexType<A> = If<
  Or<Extends<A, number>, Extends<A, boolean>>,
  number,
  string
>;

Install

$ npm install typescript-conditional-types

You'll probably want to save it in the devDependencies

Type Helper List

  • If<Condition, Then, Else>: If Condition is true resulting type is Then else Else
  • And<A, B>: true if A and B are both true else false
  • Or<A, B>: true if A or B are true else false
  • Not: Negate A
  • Extends<A, B>: true if A extends B like in A extends B ? true : false
  • Extends<A, B, Then, Else: Equivalent to If<Extends<A, B>, Then, Else>

Usage Example

import { If } from "typescript-conditional-types";
 
type BooleanToString<T extends boolean> = If<T, "true", "false">
 
BooleanToString<true> // "true"
BooleanToString<false> // "false"

Dependents (0)

Package Sidebar

Install

npm i typescript-conditional-types

Weekly Downloads

4

Version

1.0.0

License

MIT

Unpacked Size

4.68 kB

Total Files

6

Last publish

Collaborators

  • danielpanpm