Skip to content

Instantly share code, notes, and snippets.

@keigoi
Created October 13, 2020 02:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save keigoi/2c2a059e0bd21c46b8479302c5908303 to your computer and use it in GitHub Desktop.
Save keigoi/2c2a059e0bd21c46b8479302c5908303 to your computer and use it in GitHub Desktop.
TypeScript type equality and union types
// 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