Skip to content

/web-error-handling-result-types

TypeScript Result/Either types for type-safe error handling, railway-oriented programming patterns, error as values

shell
$ npx -y skills add agents-inc/skills --skill web-error-handling-result-types --agent claude-code

How it fires

How this skill gets triggered: by you, by Claude, or both.

  • Fires itselfAuto-invocation. Claude auto-loads it when your prompt matches the work.
  • You can call itInvoke it directly when you want it.
  • Slash command/web-error-handling-result-types
How auto-invocation works

Context preview

The summary Claude sees to decide when to auto-load this skill.

TypeScript Result/Either types for type-safe error handling, railway-oriented programming patterns, error as values

SKILL.md

web-error-handling-result-types.SKILL.md
name: web-error-handling-result-types
description: TypeScript Result/Either types for type-safe error handling, railway-oriented programming patterns, error as values

TypeScript Result Type Patterns

> **Quick Guide:** Result types make errors explicit in function signatures, forcing callers to handle both success and failure cases. Use for expected/recoverable errors (validation, API calls, parsing). Keep exceptions for truly exceptional situations (programming bugs, unrecoverable errors). Result types are ~300x faster than exceptions.

---

<critical_requirements>

CRITICAL: Before Using This Skill

> **All code must follow project conventions in CLAUDE.md** (kebab-case, named exports, import ordering, `import type`, named constants)

**(You MUST check result.ok before accessing result.value or result.error - TypeScript enforces this)**

**(You MUST wrap ALL throwable operations (JSON.parse, etc.) in tryCatch when inside Result-returning functions)**

**(You MUST use typed error objects with discriminant properties (code, type) - NOT generic Error or string)**

**(You MUST handle ALL Result values - never ignore return value of Result-returning functions)**

**(You MUST use flatMap/andThen for chaining Results - NOT nested if statements)**

</critical_requirements>

---

**Auto-detection:** Result type, Either type, ok err, railway-oriented programming, error as value, flatMap andThen, tryCatch, neverthrow, Effect Either, discriminated union error, typed errors, error handling Result

**When to use:**

  • Handling expected, recoverable errors (validation, parsing, API calls)
  • Building APIs where callers need to know all failure modes
  • Performance-critical code (Results are ~300x faster than exceptions)
  • Creating explicit error contracts in function signatures
  • Chaining operations that may fail (railway-oriented programming)

**Key patterns covered:**

  • Basic Result type definition and usage
  • Mapping success and error values
  • Chaining operations with flatMap/andThen
  • Combining multiple Results (fail-fast and collect-all)
  • Wrapping throwable operations
  • Async Result patterns
  • Pattern matching on Results

**When NOT to use:**

  • Truly exceptional/unexpected situations (use exceptions)
  • Unrecoverable errors (configuration missing at startup)
  • Optional values without error info (use `T | null` or Option type)
  • Simple boolean checks (use plain boolean)
  • Framework boundaries that expect exceptions (framework error handlers)

**Detailed Resources:**

  • For code examples, see [examples/core.md](examples/core.md)
  • For async patterns, see [examples/async.md](examples/async.md)
  • For combining multiple Results, see [examples/combining.md](examples/combining.md)
  • For decision frameworks and anti-patterns, see [reference.md](reference.md)

---

<philosophy>

Philosophy

Result types bring **errors into the type system**, making them impossible to ignore. Unlike exceptions which create hidden control flow, Results are values that must be explicitly handled. The key principle is **errors as data** - a function that can fail returns `Result<T, E>` where both success and failure are first-class citizens.

**Core principles:**

1. **Explicit over implicit** - Function signatures show exactly what can go wrong 2. **Composition over nesting** - Chain operations with map/flatMap instead of nested if/try 3. **Type safety over runtime checks** - TypeScript prevents accessing wrong property 4. **Performance over convenience** - Results are ~300x faster than throwing exceptions

**The Railway Metaphor:**

Think of operations as railway tracks. Success keeps you on the main track. Errors switch you to the error track. Once on the error track, subsequent operations are skipped until you explicitly handle the error.

     parseNumber     validatePositive     double
OK   ─────────────────────────────────────────────> success
                  ↘                  ↘
ERR                 ────────────────────────────> failure

</philosophy>

---

<patterns>

Core Patterns

Pattern 1: Basic Result Type Definition

The minimal Result type uses a discriminated union with `ok` as the discriminant.

Type Definition

// result.ts - Zero-dependency implementation
export type Result<T, E = Error> =
  | { readonly ok: true; readonly value: T }
  | { readonly ok: false; readonly error: E };

// Constructor functions
export const ok = <T>(value: T): Result<T, never> => ({
  ok: true,
  value,
});

export const err = <E>(error: E): Result<never, E> => ({
  ok: false,
  error,
});

**Why good:** Discriminated union enables TypeScript narrowing, readonly prevents mutation, `never` in constructors enables type inference, zero dependencies

Usage

// ✅ Good Example - Explicit error handling
interface DivisionError {
  code: "DIVISION_BY_ZERO";
  message: string;
}

const DIVISION_BY_ZERO_ERROR: DivisionError = {
  code: "DIVISION_BY_ZERO",
  message: "Cannot divide by zero",
};

function divide(a: number, b: number): Result<number, DivisionError> {
  if (b === 0) {
    return err(DIVISION_BY_ZERO_ERROR);
  }
  return ok(a / b);
}

// TypeScript FORCES handling both cases
const result = divide(10, 2);
if (result.ok) {
  console.log(`Result: ${result.value}`); // TypeScript knows: number
} else {
  console.error(`Error: ${result.error.message}`); // TypeScript knows: DivisionError
}

**Why good:** Error handling is mandatory (not optional), TypeScript narrows types in each branch, error type is known and actionable, pre-created error object avoids allocation in hot paths

// ❌ Bad Example - Ignoring Result
function process(input: string): void {
  divide(10, 0); // Result is discarded!
  console.log("Done"); // Continues as if nothing went wrong
}

**Why bad:** Defeats the purpose of Result types - errors are silently ignored, no type error because void function discards all returns

---

Pattern 2: Mapping Values (map and m

Read more
Read it on GitHub ↗

Showing the first part of this file.

Ships withagents-inc-skills

The official skills marketplace for Agents Inc. 150+ skills covering everything from React and Prisma to Redis, ElevenLabs, and infrastructure tooling. Pick the skills that match your stack and install them via Claude Code. Need more control?

Get the whole plugin, auto-invoked