DEV Community

Acid Coder
Acid Coder

Posted on • Edited on

1

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

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay