Typescript WTF Moments 8: Type Level Equality Not Working With Intersection

tylim88

Acid Coder

Posted on September 22, 2022

Typescript WTF Moments 8: Type Level Equality Not Working With Intersection
export type IsSame<T, U> = (<G>() => G extends T ? 1 : 2) extends <
    G
>() => G extends U ? 1 : 2
    ? true
    : false

type A = IsSame<{a:1, b:2},{a:1, b:2}> // true
//   ^?

type B = IsSame<{ a:1, b:2 },{ a:1 } & { b:2 }> // false
//   ^?
Enter fullscreen mode Exit fullscreen mode

Background: Type Level Equality

playground

Solution:

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

export type ReMap<T> = T extends Record<string, unknown>
    ? { [Key in keyof T]: T[Key] }
    : T

type A = IsSame<{ a:1, b:2 }, { a:1, b:2 }> // true
//   ^?

type B = IsSame<ReMap<{ a:1, b:2 }>, ReMap<{ a:1 } & { b:2 }>> // true
//   ^?

Enter fullscreen mode Exit fullscreen mode

playground

Combine Remap and IsSame

💖 💪 🙅 🚩
tylim88
Acid Coder

Posted on September 22, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related