feat(typescript-types): Add If<Test,TrueBranch,FalseBranch>
This commit is contained in:
@@ -8,10 +8,14 @@ The types included in this library are categorized by their purpose.
|
||||
|
||||
#### Test Types
|
||||
|
||||
| Type | Description |
|
||||
| ---------------- | ------------------------------------------------------------------------------------------- |
|
||||
| [`IsAny<T>`][] | `true` if `T` is `any`, `false` otherwise (`null`, `undefined` also yield `false`) |
|
||||
| [`IsNever<T>`][] | `true` if `T` is `never`, `false` otherwise (`null`, `undefined`, `any` also yield `false`) |
|
||||
| Type | Description |
|
||||
| --------------------------------------- | ------------------------------------------------------------------------------------------- |
|
||||
| [`IsAny<T>`][] | `true` if `T` is `any`, `false` otherwise (`null`, `undefined` also yield `false`) |
|
||||
| [`IsNever<T>`][] | `true` if `T` is `never`, `false` otherwise (`null`, `undefined`, `any` also yield `false`) |
|
||||
| [`If<Test, TrueBranch, FalseBranch>`][] | Returns `TrueBranch` if `Test` is `true`, `FalseBranch` otherwise[^if_remark]. |
|
||||
|
||||
[^if_remark]: Note the special behavior, if `boolean` is passed as `Test` the return value is a union of both branches, i.e. `TrueBranch | FalseBranch`.
|
||||
|
||||
[`IsAny<T>`]: src/is-any.ts
|
||||
[`IsNever<T>`]: src/is-never.ts
|
||||
[`If<Test, TrueBranch, FalseBranch>`]: src/if.ts
|
||||
|
||||
13
packages/typescript-types/src/if.ts
Normal file
13
packages/typescript-types/src/if.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import type { IsAny } from './is-any.js'
|
||||
import type { IsNever } from './is-never.js'
|
||||
|
||||
// Note: Returns a union of TrueBranch and FalseBranch if Test is any or boolean
|
||||
// Note: Returns FalseBranch if Test is never
|
||||
export type If<Test, TrueBranch, FalseBranch> =
|
||||
IsAny<Test> extends true
|
||||
? FalseBranch
|
||||
: IsNever<Test> extends true
|
||||
? FalseBranch
|
||||
: Test extends true
|
||||
? TrueBranch
|
||||
: FalseBranch
|
||||
10
packages/typescript-types/test/if.tst.ts
Normal file
10
packages/typescript-types/test/if.tst.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import type { If } from '@/if.js'
|
||||
import { expect } from 'tstyche'
|
||||
|
||||
expect<If<true, 'Y', 'N'>>().type.toBe<'Y'>()
|
||||
|
||||
expect<If<false, 'Y', 'N'>>().type.toBe<'N'>()
|
||||
expect<If<never, 'Y', 'N'>>().type.toBe<'N'>()
|
||||
expect<If<any, 'Y', 'N'>>().type.toBe<'N'>()
|
||||
|
||||
expect<If<boolean, 'Y', 'N'>>().type.toBe<'Y' | 'N'>()
|
||||
Reference in New Issue
Block a user