Coding problem · Medium · Language Idioms
Result Type Instead of Exceptions
Medium Language practicals Seen at Stripe, Vercel, Linear
Define type Result<T, E> = { ok: true; value: T } | { ok: false; error: E } and implement:
parseAge(input: string): Result<number, string>- trim the input; it must be digits only, otherwise
{ ok: false, error: "not a number" }; - the value must be between 0 and 150 inclusive, otherwise
{ ok: false, error: "out of range" }.
- trim the input; it must be digits only, otherwise
tryCatch<T>(fn: () => T): Result<T, Error>— runfn; returnokwith its value, orok: falsewith the thrown value (wrap non-Errorthrows in anError).
Hints
Hint 1
The ok literal type is the discriminant: after if (r.ok), TypeScript knows r.value exists.
Hint 2
A regex like /^\d+$/ rejects -5, 4.2 and ''.
Write and run your solution
Loading the editor… (JavaScript is required to run code in your browser.)
Solution and explanation
Show the solution
Time O(length of input) · Space O(1)
A discriminated union makes failure part of the return type, so callers must handle it — the compiler narrows r.value vs r.error after checking r.ok. This is the style of Rust's Result, and of libraries like neverthrow.
catch (e) gives you unknown under strict (useUnknownInCatchVariables), so normalise it into an Error before returning it.
Reference solution
type Result<T, E> = { ok: true; value: T } | { ok: false; error: E };
function parseAge(input: string): Result<number, string> {
const text = input.trim();
if (!/^\d+$/.test(text)) return { ok: false, error: "not a number" };
const age = Number(text);
if (age > 150) return { ok: false, error: "out of range" };
return { ok: true, value: age };
}
function tryCatch<T>(fn: () => T): Result<T, Error> {
try {
return { ok: true, value: fn() };
} catch (e) {
return { ok: false, error: e instanceof Error ? e : new Error(String(e)) };
}
}
Common mistakes
Number("")is0andparseInt("12abc")is12— validate the text first.- Assuming the caught value is an
Error.
Follow-up questions
- Add
mapandandThenhelpers. - Make
tryCatchAsyncfor promises.