|
| 1 | +# typescript-conditional-types |
| 2 | + |
| 3 | +[](https://www.npmjs.com/package/typescript-conditional-types) |
| 4 | +[](https://conventionalcommits.org) |
| 5 | +[](https://github.com/prettier/prettier) |
| 6 | + |
| 7 | +Helpers for typescript generic types |
| 8 | + |
| 9 | +## Motivation |
| 10 | + |
| 11 | +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. |
| 12 | + |
| 13 | +Instead of |
| 14 | + |
| 15 | +```ts |
| 16 | +type ComplexType<A> = A extends boolean |
| 17 | + ? number |
| 18 | + : A extends number ? number : string |
| 19 | + : string |
| 20 | +``` |
| 21 | +
|
| 22 | +You could write |
| 23 | +
|
| 24 | +```ts |
| 25 | +type ComplexType<A> = If< |
| 26 | + Or<Extends<A, number>, Extends<A, boolean>>, |
| 27 | + number, |
| 28 | + string |
| 29 | +>; |
| 30 | +``` |
| 31 | + |
| 32 | +## Install |
| 33 | + |
| 34 | +```bash |
| 35 | +$ npm install typescript-conditional-types |
| 36 | +``` |
| 37 | + |
| 38 | +You'll probably want to save it in the _devDependencies_ |
| 39 | + |
| 40 | +## Type Helper List |
| 41 | + |
| 42 | +- _If<Condition, Then, Else>_: If _Condition_ is `true` resulting type is _Then_ else _Else_ |
| 43 | +- _And<A, B>_: `true` if _A_ and _B_ are both `true` else `false` |
| 44 | +- _Or<A, B>_: `true` if _A_ or _B_ are `true` else `false` |
| 45 | +- _Not<A>_: Negate _A_ |
| 46 | +- _Extends<A, B>_: `true` if _A_ extends _B_ like in `A extends B ? true : false` |
| 47 | +- _Extends<A, B, Then, Else_: Equivalent to `If<Extends<A, B>, Then, Else>` |
| 48 | + |
| 49 | +## Usage Example |
| 50 | + |
| 51 | +```ts |
| 52 | +import { If } from "typescript-conditional-types"; |
| 53 | + |
| 54 | +type BooleanToString<T extends boolean> = If<T, "true", "false"> |
| 55 | + |
| 56 | +BooleanToString<true> // "true" |
| 57 | +BooleanToString<false> // "false" |
| 58 | +``` |
0 commit comments