Created
October 13, 2020 02:57
-
-
Save keigoi/2c2a059e0bd21c46b8479302c5908303 to your computer and use it in GitHub Desktop.
TypeScript type equality and union types
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// returns the intersection of all elements in the union T | |
// i.e. ToIntersect<T1 | T2 | .. | Tn> = T1 & T2 & .. & Tn | |
type ToIntersect<T> = (T extends unknown ? (x:T) => void : never) extends (x:infer U) => void ? U : never; | |
// check if T and U are equal | |
// Here, ([T] extends [U] ? _ : _) suppresses union distribution. | |
// See: https://github.com/microsoft/TypeScript/issues/29368 | |
type Eq<T,U> = [T] extends [U] ? [U] extends [T] ? true : false : false; | |
// check if all elements in the union LS are equal by using (T & U) = (T | U) iff T = U | |
type EqAll<LS> = Eq<ToIntersect<LS>, LS> | |
type X = EqAll<{a:"1"} | {a:"1"}> // true | |
type Y = EqAll<{a:"1"} | {a:"1", b:"2"}> // false | |
type Z = EqAll<{b:"2", a:"1"} | {a:"1", b:"2"}> // true | |
type W = EqAll<{a:"1"|"2"} | {a:"1"}> // false | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment