Skip to content

Instantly share code, notes, and snippets.

@zeusdeux
Created January 5, 2019 17:39
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 zeusdeux/22b0ad713944b0914ec8e7e887ae0d38 to your computer and use it in GitHub Desktop.
Save zeusdeux/22b0ad713944b0914ec8e7e887ae0d38 to your computer and use it in GitHub Desktop.
Sum types with never in typescript
// never is dropped from sum types
let x: string | never // string
let y: Exclude<'a' | 'b', 'b'> // y has the type 'a'
/*
* Explanation:
* Given that Exclude is defined as: type Exclude<T, U> = T extends U ? never : T
* Exclude<'a' | 'b', 'b'> checks if 'a' extends 'b'.
* It doesn't and hence 'a' is returned
* Type system then checks if 'b' extends 'b'.
* It does and hence `never` is returned.
* The resultant type is 'a' | never which resolves to just 'a'
* This is why variable `y` has the type 'a'
* /
// https://til.mudit.xyz/12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment