ts-if
TypeScript icon, indicating that this package has built-in type declarations

1.0.147 • Public • Published

ts-if

- Typescript if-else support at the type level

Description

Typescript's conditional types are powerful but they do only support ternaries, which makes the code hard to manage.

Ts-if is a library which adds if-elseif-else support at the type level which greatly improves readability and thus manageability of the code - especially when working in teams.

Installation

npm install ts-if

Example 1

import type { If, Return } from 'ts-if';

type Password = 'abc123';

type Result = If<Password, '==', 'abc123', (
    Return<'Access granted'>
)>

type x = Result;
//   ^? Access granted

Example 2

import type { If, Else, Return } from 'ts-if';

interface Person {
    firstname: string;
    lastname: string;
    age: number;
}

type Foo = If<'firstname', 'in', Person, (
    Return<Person['firstname']>
),
Else<(
    Return<null>
)>>

type zz = Foo;
//   ^? string

Example 3

import type { If, ElseIf, Else, Return } from 'ts-if';

type Fruit = 'pineapples';

type MyType = If<Fruit, '==', 'oranges', (
    Return<'oranges'>
),

ElseIf<Fruit, '==', 'pineapples', (
    Return<'pineapples'>
),

ElseIf<Fruit, '==', 'apples', (
    Return<'apples'>
),

Else<(
    Return<'Nothing'>
)>>>>;

let foo:MyType;
//    ^? pineapples

Contact

jonas@doctorbirch.com

Package Sidebar

Install

npm i ts-if

Weekly Downloads

156

Version

1.0.147

License

MIT

Unpacked Size

5.48 kB

Total Files

6

Last publish

Collaborators

  • dr-jonas