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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With