Result Type For Error Handling
Implement a Result type for explicit error handling without exceptions forcing callers to handle both cases.
Code
export type Result<T,E=Error>= {ok:true;value:T}|{ok:false;error:E};export function ok<T>(value:T):Result<T,never>{return{ok:true,value};}export function err<E>(error:E):Result<never,E>{return{ok:false,error};}export function unwrap<T,E>(r:Result<T,E>):T{if(r.ok)return r.value;throw r.error;}export function map<T,U,E>(r:Result<T,E>,fn:(v:T)=>U):Result<U,E>{return r.ok?ok(fn(r.value)):r;}export function flatMap<T,U,E>(r:Result<T,E>,fn:(v:T)=>Result<U,E>):Result<U,E>{return r.ok?fn(r.value):r;}export async function fromPromise<T>(p:Promise<T>):Promise<Result<T,Error>>{try{return ok(await p);}catch(e){return err(e as Error);}}How the snippet works
The code’s whole job belongs to the functions ok, err, unwrap and map.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
The result comes back as an object carrying true.
What to watch for
- The guard
r.okshort-circuits the flow with an earlyreturnwhen its condition holds.
Applying it
Import ok from the file and call it — the rest of the code is implementation detail.
The call returns true.
Interactive Tools for This Topic
FAQ
- Can I paste this into a project as-is?
- Yes. Paste it in and run; no package manager step is needed. The file defines `ok`, `err`, `unwrap` at load time.
- What does `ok` return?
- An object carrying `true`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.