Skip to content

Commit

Permalink
feat(Conditionals): Add IsUnion and corresponding Ifs
Browse files Browse the repository at this point in the history
  • Loading branch information
SirWrexes committed Jun 27, 2023
1 parent 9899345 commit 66701bc
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
12 changes: 11 additions & 1 deletion tests/Util.test.d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Equal, Expect, PartialExcept } from '../types'
import { Equal, Expect, ExpectFalse, ExpectTrue, IsUnion, PartialExcept } from '../types'

declare namespace PartialExcept {
interface Dummy {
Expand All @@ -19,4 +19,14 @@ type __TEST__ = {
>,
Expect<Equal<PartialExcept<PartialExcept.Dummy, never>, Partial<PartialExcept.Dummy>>>
]
IsUnion: [
ExpectTrue<IsUnion<'sauce' | 'blanche'>>,
ExpectTrue<IsUnion<string | number>>,
ExpectFalse<IsUnion<never>>,
ExpectFalse<IsUnion<string>>,
// `string | 'a literal'` evaluates to string
ExpectFalse<IsUnion<string | 'sauce'>>,
// `string | never` evalutates to string
ExpectFalse<IsUnion<string | never>>
]
}
11 changes: 11 additions & 0 deletions types/Conditionals.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,3 +63,14 @@ export type IfAny<Type, OnIsAny, OnIsNotAny = never> = If<IsAny<Type>, OnIsAny,
export type IfNotAny<Type, OnIsNotAny, OnIsAny = never> = If<IsNotAny<Type>, OnIsNotAny, OnIsAny>

export type IsObject<Type> = Extends<Type, object>

type __IsUnion<T, U> = IfNotNever<T, T extends U ? ([U] extends [T] ? false : true) : never, false>
export type IsUnion<T> = __IsUnion<T, T>
export type IsNotUnion<T> = Not<IsUnion<T>>

export type IfUnion<T, OnIsUnion, OnIsNotUnion = never> = If<IsUnion<T>, OnIsUnion, OnIsNotUnion>
export type IfNotUnion<T, OnIsNotUnion, OnIsUnion = never> = If<
IsNotUnion<T>,
OnIsNotUnion,
OnIsUnion
>

0 comments on commit 66701bc

Please sign in to comment.