TypeScript (Style Guide)
Overview
Produce TypeScript that is easy to read, easy to change, and safe at runtime—by treating the codebase as a system: explicit boundaries, explicit dependencies, explicit errors, and explicit lifetimes.
Most of the principles here translate to other languages; the TypeScript-specific parts are mainly about how to enforce them with TS tooling and types.
Default objectives:
- Consistency: prefer automated formatting and linting (Prettier + ESLint) to eliminate style drift.
- Readability: reduce cognitive load with clear naming, shallow control flow, and explicit types.
- Maintainability: keep modules cohesive and dependencies/lifetimes explicit so change stays local.
A note on scope: these guidelines are optimized for systemic TypeScript (long‑lived apps/services/libraries where ownership, I/O boundaries, and runtime behavior matter). For short‑lived scripts, you can relax some constraints (e.g. more throw, fewer abstractions) as long as the blast radius stays small.
Definitions:
- Scriptic: short‑lived scripts/one‑offs; optimize for speed and simplicity;
throw is usually fine.
- Systemic: long‑lived apps/services/libraries; optimize for explicit boundaries, typed failures, and explicit lifetimes.
Workflow (default)
- Decide “scriptic vs systemic” and set policies (error strategy, boundary validation, ownership/lifetimes).
- Separate pure logic from side effects (I/O, time, randomness, global state).
- Identify boundaries (HTTP/DB/fs/env) and treat their inputs as
unknown.
- Model the domain with types (discriminated unions) and keep data as plain objects (serializable).
- Apply the Throwless Pact: make known failures explicit in types; reserve
throw for unknown/unrecoverable; catch and convert at boundaries.
- Keep dependencies explicit via parameters/factories; centralize wiring in a composition root.
- Keep the module graph acyclic; enforce a dependency direction; prefer
import type for type-only imports.
- Make lifetimes explicit (create/start/stop/dispose); don’t rely on GC or hidden ownership.
- For long‑running work (pollers, consumers, schedulers), model explicit “agents” with typed inputs/state and explicit shutdown.
- Test at seams (pure functions, decoders/validators, adapters).
- At I/O boundaries, make timeouts/retries/idempotency explicit (
resilience) and keep telemetry consistent (observability); if 2+ services need the same boundary primitive, extract it (see platform).
Guidelines
For the full set of guidelines, see references/guidelines.md. Key highlights:
- Systemic constraints: types are erased at runtime,
throw is untyped, serialization is not bijective, no deterministic destructors, cyclic deps break systems.
- Throwless Pact: known failures as typed
Result / tagged unions; reserve throw for unknown/unrecoverable; catch at boundaries.
- Boundaries: treat external inputs as
unknown; validate/parse once at the edge; keep "wire" shapes separate from domain types.
- Lifetimes: make resource ownership explicit (create/start/stop/dispose); prefer
AbortSignal for cancellation.
- Modules: prevent cyclic imports; use a composition root; one feature per file; avoid barrel exports across layers.
References
Review checklist
Use this list when reviewing/refactoring TypeScript:
- Names are precise; no mystery abbreviations or misleading types.
- Formatting/imports follow the formatter (Prettier/ESLint); import order is stable.
- Functions are small, single-purpose, and mostly pure; few parameters; no boolean flags.
- Control flow is readable: shallow indentation, no nested ternaries, and no “clever” one-liners.
- Discriminated unions are handled exhaustively; missing variants fail fast at compile time.
- No accidental
any; unknown is narrowed/decoded before use.
- External input is validated/decoded at boundaries; no unsafe
as casts from JSON/env/network input.
- JSON/env/DB “wire” shapes are kept separate from domain types; round-trips don’t silently lose meaning.
- Expected failures are signified (tagged unions /
Result); no sentinel returns; internal code is effectively “throwless”.
- Boundary code catches unknown throws and converts them to known error variants.
- Errors aren’t logged repeatedly across layers; logging happens at boundaries with enough context.
- Side effects are isolated; module dependencies are explicit and acyclic.
- No top-level side effects; composition root owns startup/shutdown.
- Resource ownership/cleanup is explicit; no “leaky” lifetimes; cancellation is threaded via
AbortSignal.
- Long-running loops are explicit agents with shutdown/await paths.
- Tests cover pure logic and boundary adapters (decoders, repositories, clients).
Output template
When asked to apply this guide, respond with:
- Start with the highest-leverage changes (usually around boundaries, error signifiers, and lifetimes/ownership).
- Concrete refactors (diffs or patch-sized snippets).
- Any trade-offs and clarifying questions (scriptic vs systemic scope, domain boundaries, lifetime/agent ownership, error policy).
1---2name: typescript-143description: Write, review, and refactor TypeScript for readability, type safety, and runtime correctness (Node.js/React/shared libs). Use when creating TS modules, modeling domain types, handling errors (Result/Either), validating external inputs (Zod/io-ts), organizing imports, or preventing cyclic dependencies. NOT for choosing design patterns (use design); NOT for shared platform library design (use platform).4---5
6# TypeScript (Style Guide)
7
8## Overview
9
10Produce TypeScript that is easy to read, easy to change, and safe at runtime—by treating the codebase as a *system*: explicit boundaries, explicit dependencies, explicit errors, and explicit lifetimes.
11
12Most of the principles here translate to other languages; the TypeScript-specific parts are mainly about how to enforce them with TS tooling and types.
13
14Default objectives:
15
16- **Consistency**: prefer automated formatting and linting (Prettier + ESLint) to eliminate style drift.
17- **Readability**: reduce cognitive load with clear naming, shallow control flow, and explicit types.
18- **Maintainability**: keep modules cohesive and dependencies/lifetimes explicit so change stays local.
19
20A note on scope: these guidelines are optimized for **systemic** TypeScript (long‑lived apps/services/libraries where ownership, I/O boundaries, and runtime behavior matter). For short‑lived scripts, you can relax some constraints (e.g. more `throw`, fewer abstractions) as long as the blast radius stays small.
21
22Definitions:
23
24- **Scriptic**: short‑lived scripts/one‑offs; optimize for speed and simplicity; `throw` is usually fine.
25- **Systemic**: long‑lived apps/services/libraries; optimize for explicit boundaries, typed failures, and explicit lifetimes.
26
27## Workflow (default)
28
291. Decide “scriptic vs systemic” and set policies (error strategy, boundary validation, ownership/lifetimes).
302. Separate pure logic from side effects (I/O, time, randomness, global state).
313. Identify boundaries (HTTP/DB/fs/env) and treat their inputs as `unknown`.
324. Model the domain with types (discriminated unions) and keep data as plain objects (serializable).
335. Apply the *Throwless Pact*: make known failures explicit in types; reserve `throw` for unknown/unrecoverable; catch and convert at boundaries.
346. Keep dependencies explicit via parameters/factories; centralize wiring in a composition root.
357. Keep the module graph acyclic; enforce a dependency direction; prefer `import type` for type-only imports.
368. Make lifetimes explicit (create/start/stop/dispose); don’t rely on GC or hidden ownership.
379. For long‑running work (pollers, consumers, schedulers), model explicit “agents” with typed inputs/state and explicit shutdown.
3810. Test at seams (pure functions, decoders/validators, adapters).
3911. At I/O boundaries, make timeouts/retries/idempotency explicit (`resilience`) and keep telemetry consistent (`observability`); if 2+ services need the same boundary primitive, extract it (see `platform`).
40
41## Guidelines
42
43For the full set of guidelines, see [`references/guidelines.md`](references/guidelines.md). Key highlights:
44
45- **Systemic constraints**: types are erased at runtime, `throw` is untyped, serialization is not bijective, no deterministic destructors, cyclic deps break systems.
46- **Throwless Pact**: known failures as typed `Result` / tagged unions; reserve `throw` for unknown/unrecoverable; catch at boundaries.
47- **Boundaries**: treat external inputs as `unknown`; validate/parse once at the edge; keep "wire" shapes separate from domain types.
48- **Lifetimes**: make resource ownership explicit (create/start/stop/dispose); prefer `AbortSignal` for cancellation.
49- **Modules**: prevent cyclic imports; use a composition root; one feature per file; avoid barrel exports across layers.
50
51## References
52
53- Glossary for common terms: [`GLOSSARY.md`](../../GLOSSARY.md)
54- Specs/contracts as sources of truth: [`spec`](../spec/SKILL.md)
55- Boundary time budgets and idempotency: [`resilience`](../resilience/SKILL.md)
56- Telemetry consistency: [`observability`](../observability/SKILL.md)
57- Shared “golden path” primitives: [`platform`](../platform/SKILL.md)
58
59## Review checklist
60
61Use this list when reviewing/refactoring TypeScript:
62
63- Names are precise; no mystery abbreviations or misleading types.
64- Formatting/imports follow the formatter (Prettier/ESLint); import order is stable.
65- Functions are small, single-purpose, and mostly pure; few parameters; no boolean flags.
66- Control flow is readable: shallow indentation, no nested ternaries, and no “clever” one-liners.
67- Discriminated unions are handled exhaustively; missing variants fail fast at compile time.
68- No accidental `any`; `unknown` is narrowed/decoded before use.
69- External input is validated/decoded at boundaries; no unsafe `as` casts from JSON/env/network input.
70- JSON/env/DB “wire” shapes are kept separate from domain types; round-trips don’t silently lose meaning.
71- Expected failures are signified (tagged unions / `Result`); no sentinel returns; internal code is effectively “throwless”.
72- Boundary code catches unknown throws and converts them to known error variants.
73- Errors aren’t logged repeatedly across layers; logging happens at boundaries with enough context.
74- Side effects are isolated; module dependencies are explicit and acyclic.
75- No top-level side effects; composition root owns startup/shutdown.
76- Resource ownership/cleanup is explicit; no “leaky” lifetimes; cancellation is threaded via `AbortSignal`.
77- Long-running loops are explicit agents with shutdown/await paths.
78- Tests cover pure logic and boundary adapters (decoders, repositories, clients).
79
80## Output template
81
82When asked to apply this guide, respond with:
83
84- Start with the highest-leverage changes (usually around boundaries, error signifiers, and lifetimes/ownership).
85- Concrete refactors (diffs or patch-sized snippets).
86- Any trade-offs and clarifying questions (scriptic vs systemic scope, domain boundaries, lifetime/agent ownership, error policy).