TypeScript Error Handling Patterns
Model errors using types instead of throwing blindly, building safer and more predictable flows.
David Miller
January 13, 2026
0.5k10
Errors should also be typed.
## Result pattern
```ts
type Ok<T> = { ok: true; value: T };
type Err = { ok: false; error: string };
type Result<T> = Ok<T> | Err;
```
## Function returning Result
```ts
function parseNum(s: string): Result<number> {
const n = Number(s);
return isNaN(n) ? { ok: false, error: "Not a number" } : { ok: true, value: n };
}
```
## Use it
```ts
const r = parseNum("10");
if (r.ok) {
console.log(r.value);
} else {
console.error(r.error);
}
```
## Graph
```mermaid
flowchart TD
A[Function] --> B{ok?}
B -->|Yes| C[Value]
B -->|No| D[Error]
```
## Remember
- Types can model success and failure
- Reduces runtime surprises
#TypeScript#Advanced#Error Handling