DEV Community

Acid Coder
Acid Coder

Posted on • Edited on

Typescript WTF Moments 6: Non Collapsing Object Unions

Object unions of same type do not collapse

type a = 1 | 1 // 1, collapsed
//   ^?

type b = { a:1 } | { a:1 } // { a:1 } | { a:1 }, do not collapse
//   ^?

type c = { a:1 } | { a:1 } | { a:1 } // { a:1 } | { a:1 } | { a:1 }, do not collapse
//   ^?
Enter fullscreen mode Exit fullscreen mode

playground

this should be fine most of the time but it can be problematic if we use identical check on it

union is equal to union, but not equal to non union

type o = 1 | 1 // 1
//   ^?

type p = { c:1 } | { c:1 } //  { c:1 } | { c:1 }, what?
//   ^?


type IsSame<T, U> = (<G>() => G extends T ? 1 : 2) extends <
    G
>() => G extends U ? 1 : 2
    ? true
    : false

type q = IsSame<p, {c:1 }> // false, huh?
//   ^?

type r = IsSame<p, {c:1 } | {c:1}> // true, ok
//   ^?

type s = IsSame<p, {c:1 } | {c:1} | {c:1}> // true, huh?
//   ^?

type k = IsSame<p, {c:1 } | {c:1} | {c:1} | {c:1}> // true, huh?
//   ^?
Enter fullscreen mode Exit fullscreen mode

Image description

playground

Top comments (0)