Typescript WTF Moments 6: Non Collapsing Object Unions
Acid Coder

Acid Coder @tylim88

About: Who needs meth when you have Typescript?

Joined:
Oct 31, 2021

Typescript WTF Moments 6: Non Collapsing Object Unions

Publish Date: Aug 19 '22
2 0

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

Comments 0 total

    Add comment