ts-if
v1.0.147
Published
Typescript if-else support at the type level
Downloads
216
Maintainers
Readme
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