typescript / intermediate
Snippet
Type-Safe Functional Error Handling using Result Wrappers
Instead of relying on unhandled exception throwing, explicit Result types model outcomes using a success boolean flag. This forces callers to check the result state before accessing the success value or handling the error message.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
type Ok<T> = { readonly success: true; readonly value: T };type Err<E> = { readonly success: false; readonly error: E };type Result<T, E> = Ok<T> | Err<E>;function ok<T>(value: T): Ok<T> {return { success: true, value };}function err<E>(error: E): Err<E> {return { success: false, error };}function parsePort(input: string): Result<number, string> {const parsed = Number(input);if (Number.isNaN(parsed) || parsed < 1 || parsed > 65535) {return err(`Invalid port number: '${input}'`);}return ok(parsed);}
Breakdown
1
type Result<T, E> = Ok<T> | Err<E>;
Defines a generic union representing either a successful output of type T or a failure error of type E.
2
function parsePort(input: string): Result<number, string> {
Returns a Result instance instead of throwing a runtime Exception when validation fails.
3
return ok(parsed);
Wraps valid output into an Ok container with success set to true.