'IsEqual util type in Typescript doesn't work as expected [duplicate]
I write a IsEqual generic type like that :
type IsEqual<T, U> = T extends U
? U extends T
? true
: false
: false
type Test1 = IsEqual<number, 3> // false, ok
type Test2 = IsEqual<true, false> // false, ok
type Test3 = IsEqual<boolean, true> // boolean -> ?
type Test4 = IsEqual<true, boolean> // boolean -> ?
What happens here ?
And how to reliably check if a type is the exact same as another ? (not a subtype)
Solution 1:[1]
You need to wrap T and U in brackets in the body of the typedef, i.e:
type IsEqual<T, U> = [T] extends [U]
? [U] extends [T]
? true
: false
: false
Otherwise, TypeScript will distribute the types and evaluate IsEqual<boolean, true> as IsEqual<true, true> | IsEqual<false, true>. Source: this github comment.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Bbrk24 |
