Result union type in TypeScript
A discriminated union for success or failure, so errors are values the compiler checks.
type Ok<T> = { ok: true; value: T };
type Err = { ok: false; error: string };
type Result<T> = Ok<T> | Err;
function unwrap<T>(result: Result<T>): T {
if (result.ok) {
return result.value;
}
throw new Error(result.error);
}
Keywords and builtins used here
ResultTfalsefunctionifreturnstringthrowtruetype
The run, in numbers
- Lines
- 10
- Characters to type
- 224
- Tokens
- 81
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 46 seconds.
Step 2 of 4 in Results & validation, step 6 of 19 in Classes & patterns.