Error Handling and Validation
Result-Style Unions
A result union returns either a success value or an error message without throwing.
Result-Style Unions
result.ts
type ParseResult =
| { ok: true; value: number }
| { ok: false; error: string };
function parseCount(text: string): ParseResult {
const value: number = Number(text);
if (Number.isNaN(value)) {
return { ok: false, error: "not a number" };
}
return { ok: true, value: value };
}
const rawCount: string = ;
const parsed: ParseResult = parseCount(rawCount);
if (parsed.ok) {
console.log(`count=${parsed.value}`);
} else {
console.log(`error=${parsed.error}`);
}
type ParseResult =
| { ok: true; value: number }
| { ok: false; error: string };
function parseCount(text: string): ParseResult {
const value: number = Number(text);
if (Number.isNaN(value)) {
return { ok: false, error: "not a number" };
}
return { ok: true, value: value };
}
const rawCount: string = ;
const parsed: ParseResult = parseCount(rawCount);
if (parsed.ok) {
console.log(`count=${parsed.value}`);
} else {
console.log(`error=${parsed.error}`);
}
type ParseResult =
| { ok: true; value: number }
| { ok: false; error: string };
function parseCount(text: string): ParseResult {
const value: number = Number(text);
if (Number.isNaN(value)) {
return { ok: false, error: "not a number" };
}
return { ok: true, value: value };
}
const rawCount: string = ;
const parsed: ParseResult = parseCount(rawCount);
if (parsed.ok) {
console.log(`count=${parsed.value}`);
} else {
console.log(`error=${parsed.error}`);
}
result union
A result union uses a discriminant such as `ok` to separate success and failure paths.