Lesson 5 of 7
Result Type - Typed Error Handling
The Result type (also called `Either`) represents success or failure explicitly in the return type - instead of throwing exceptions. Callers must handle both cases, making error paths visible and compiler-checked. This pattern eliminates entire classes of unhandled-exception bugs.
Result<T, E> - Typed Success & Failure
// ── Result type definition ────────────────────────────────────
type Success<T> = { ok: true; value: T };
type Failure<E> = { ok: false; error: E };
type Result<T, E = Error> = Success<T> | Failure<E>;
// ── Factory helpers ────────────────────────────────────────────
const ok = <T>(value: T): Success<T> => ({ ok: true, value });
const fail = <E>(error: E): Failure<E> => ({ ok: false, error });
// ── Functions that return Result - no throws ──────────────────
async function getTaskResult(id: number): Promise<Result<Task, NotFoundError>> {
const task = await taskRepo.findById(id);
if (!task) return fail(new NotFoundError("Task", id));
return ok(task);
}
async function createTaskResult(
input: CreateTaskInput,
): Promise<Result<Task, ValidationError | ConflictError>> {
const existing = await taskRepo.findByTitle(input.title);
if (existing) return fail(new ConflictError(`Task "${input.title}" already exists`));
const task = await taskRepo.save({ ...input, id: Date.now(), createdAt: new Date(), updatedAt: new Date() } as Task);
return ok(task);
}
// ── Caller must handle both cases ────────────────────────────
const result = await getTaskResult(1);
if (result.ok) {
console.log(result.value.title); // ✅ Task
} else {
console.error(result.error.message); // ✅ NotFoundError
}
// ── Chaining Results - map / flatMap ──────────────────────────
function mapResult<T, U, E>(
result: Result<T, E>,
fn: (value: T) => U,
): Result<U, E> {
return result.ok ? ok(fn(result.value)) : result;
}
async function getTaskTitle(id: number): Promise<Result<string, NotFoundError>> {
const result = await getTaskResult(id);
return mapResult(result, (task) => task.title);
}
// ── Result vs throw - when to use each ───────────────────────
// Use Result when:
// - failure is a NORMAL part of the business flow (not found, conflict)
// - callers MUST explicitly handle the failure case
// - you want to compose error handling without try/catch nesting
//
// Use throw when:
// - the error is truly unexpected / programmer error
// - the error should propagate to a global handler
// - you're working with Express middleware where catch-all handles errorsCommon Mistakes
- Using Result everywhere including infrastructure errors - DB connection failures, file system errors, and network timeouts are exceptional. Result is for domain logic errors (not found, validation). Infrastructure errors should throw.
- Not narrowing before using `.value` - TypeScript requires narrowing: `if (result.ok) { result.value }`. Accessing `result.value` before the check gives a TS error because it might be `Failure<E>`.
- Creating complex Result chains without async awareness - chaining `.then()` on `Promise<Result<T>>` requires careful typing. Consider libraries like `fp-ts` or `neverthrow` for complex functional pipelines.
Tip
Tip
Practice Result Type Typed Error Handling in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Result Type - Typed Error Handling
Practice Task
Note
Practice Task - (1) Write a working example of Result Type Typed Error Handling from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Result Type Typed Error Handling is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready typescript code.
Key Takeaways
- The Result type (also called `Either`) represents success or failure explicitly in the return type - instead of throwing exceptions.
- Using Result everywhere including infrastructure errors - DB connection failures, file system errors, and network timeouts are exceptional. Result is for domain logic errors (not found, validation). Infrastructure errors should throw.
- Not narrowing before using `.value` - TypeScript requires narrowing: `if (result.ok) { result.value }`. Accessing `result.value` before the check gives a TS error because it might be `Failure<E>`.
- Creating complex Result chains without async awareness - chaining `.then()` on `Promise<Result<T>>` requires careful typing. Consider libraries like `fp-ts` or `neverthrow` for complex functional pipelines.
Finished this lesson?