Result/Either style types
Model success/failure explicitly with a Result/Either union, add helpers (map/flatMap/mapError), and keep flows predictable without try/catch everywhere.
Intro
Goal: Make failures visible. You will model results with a discriminated union, compose with helpers, and convert exceptions at the boundary.
- Result type
- map/flatMap/mapError
- HTTP integration
Result core
Create a small Result utility: ok/err constructors plus map, flatMap, mapError for composition.
export type Ok<T> = { ok: true; value: T }
export type Err<E> = { ok: false; error: E }
export type Result<T, E> = Ok<T> | Err<E>
export const ok = <T>(value: T): Ok<T> => ({ ok: true, value })
export const err = <E>(error: E): Err<E> => ({ ok: false, error })
export function map<T, E, U>(r: Result<T, E>, f: (t: T) => U): Result<U, E> {
return r.ok ? ok(f(r.value)) : r
}
export function flatMap<T, E, U>(r: Result<T, E>, f: (t: T) => Result<U, E>): Result<U, E> {
return r.ok ? f(r.value) : r
}
export function mapError<T, E, F>(r: Result<T, E>, g: (e: E) => F): Result<T, F> {
return r.ok ? r : err(g(r.error))
}All lessons in this course
- Result/Either style types
- Exhaustive error handling with discriminated unions