Last active
June 28, 2021 22:13
-
-
Save brettinternet/a61c866f9fe042a92e62a64214085aee to your computer and use it in GitHub Desktop.
`never` in TypeScript is an example of a bottom type
This file contains hidden or 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
/** | |
* @source https://github.com/mike-works/typescript-fundamentals/blob/4e5782e00ed942ffe8770a694122190b6ed69b95/notes/6-guards-and-extreme-types.ts | |
* A bottom type is a type case that won't match - this is `never` in TypeScript | |
*/ | |
class UnreachableError extends Error { | |
constructor(val: never, message: string) { | |
super(`TypeScript thought we could never end up here\n${message}`); | |
} | |
} | |
let y = 4 as string | number; | |
if (typeof y === "string") { | |
// y is a string here | |
y.split(", "); | |
} else if (typeof y === "number") { | |
// y is a number here | |
y.toFixed(2); | |
} else { | |
// runtime type check in case weak types escape our checks | |
throw new UnreachableError(y, "y should be a string or number"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment