Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
assert-never/index.ts
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
34 lines (33 sloc)
884 Bytes
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
/** | |
* Helper function for exhaustive checks of discriminated unions. | |
* https://basarat.gitbooks.io/typescript/docs/types/discriminated-unions.html | |
* | |
* @example | |
* | |
* type A = {type: 'a'}; | |
* type B = {type: 'b'}; | |
* type Union = A | B; | |
* | |
* function doSomething(arg: Union) { | |
* if (arg.type === 'a') { | |
* return something; | |
* } | |
* | |
* if (arg.type === 'b') { | |
* return somethingElse; | |
* } | |
* | |
* // TS will error if there are other types in the union | |
* // Will throw an Error when called at runtime. | |
* // Use `assertNever(arg, true)` instead to fail silently. | |
* return assertNever(arg); | |
* } | |
*/ | |
export default function assertNever(value: never, noThrow?: boolean): never { | |
if (noThrow) { | |
return value | |
} | |
throw new Error( | |
`Unhandled discriminated union member: ${JSON.stringify(value)}`, | |
); | |
} |