Result-typed JSON parse in TypeScript
Parses JSON into a Result rather than throwing, so the caller has to look.
type Parsed<T> = { ok: true; value: T } | { ok: false; error: string };
function safeParse<T>(raw: string): Parsed<T> {
try {
return { ok: true, value: JSON.parse(raw) as T };
} catch (err) {
return { ok: false, error: String(err) };
}
}
Keywords and builtins used here
StringTascatchfalsefunctionreturnstringtruetrytype
The run, in numbers
- Lines
- 9
- Characters to type
- 238
- Tokens
- 82
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 47 seconds.
Step 4 of 4 in Results & validation, step 8 of 19 in Classes & patterns.