1.0.0 • Published 7 years ago
typescript-conditional-types v1.0.0
typescript-conditional-types
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
: stringYou could write
type ComplexType<A> = If<
Or<Extends<A, number>, Extends<A, boolean>>,
number,
string
>;Install
$ npm install typescript-conditional-typesYou'll probably want to save it in the devDependencies
Type Helper List
- If<Condition, Then, Else>: If Condition is
trueresulting type is Then else Else - And<A, B>:
trueif A and B are bothtrueelsefalse - Or<A, B>:
trueif A or B aretrueelsefalse - Not: Negate A
- Extends<A, B>:
trueif A extends B like inA 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"1.0.0
7 years ago