Typescript WTF Moments 8: Type Level Equality Not Working With Intersection
Acid Coder
Posted on September 22, 2022
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
// ^?
Background: Type Level Equality
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
// ^?
Combine Remap
and IsSame
💖 💪 🙅 🚩
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
typescript Typescript WTF Moments 8: Type Level Equality Not Working With Intersection
September 22, 2022