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

Acid Coder @tylim88

About: Who needs meth when you have Typescript?

Joined:
Oct 31, 2021

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

Publish Date: Sep 22 '22
0 0
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

Comments 0 total

    Add comment