Created
January 5, 2019 17:39
-
-
Save zeusdeux/22b0ad713944b0914ec8e7e887ae0d38 to your computer and use it in GitHub Desktop.
Sum types with never in typescript
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
// 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