Core Philosophy
TypeScript's type system is your documentation, your test, and your specification — all at once. Make the type system encode the invariants of your domain so that invalid states are unrepresentable. Lean into the compiler.
Scope: This file covers TypeScript-specific type system and language idioms. For framework-specific patterns, see the respective idiom skill (Vue, React, Angular, Next.js, Hono). For file layout, see references/project-structure.md. For detailed safety, SAST patterns, and performance patterns, see references/ts-patterns-and-anti-patterns.md. For quality commands, see @.agents/rules/code-idioms-and-conventions.md. For logging library, see @.agents/skills/logging-implementation/SKILL.md.
Loading guards:
- Plain JavaScript (no
tsconfig.json): load @.agents/skills/javascript-idioms/SKILL.md instead — this skill assumes strict-mode TS.
- Hono backend:
hono has no repo-level marker file, so it is not auto-detected. If hono appears in package.json dependencies, co-load @.agents/skills/hono-idioms/SKILL.md alongside this skill.
- Test-file naming diverges by framework: see
references/project-structure.md § Test Organization for the reconciliation rule before creating test files.
When to Load References
Load these before writing code in the matching context — not after.
| Situation |
Reference to Load |
| Starting a new project or setting up file layout |
references/project-structure.md |
| Choosing packages, tsconfig template, or vitest config |
references/recommended-dependencies.md |
| Writing code that handles user input, async operations, or I/O |
references/ts-patterns-and-anti-patterns.md |
| Defining Zod schemas or validating API/env boundaries |
references/zod-patterns.md |
Toolchain and Runtime
- Default to latest Node.js LTS. As of July 2026, Node.js 24 LTS with TypeScript 5.8+
- ESM over CJS for all new projects
tsx for development execution (replaces ts-node)
- Key version milestones: TS 5.0+ decorators, TS 5.4+ NoInfer, TS 5.5+ inferred type predicates
Strict Mode — Non-Negotiable
All TypeScript projects MUST have strict mode enabled. If a project does not have these settings, fix tsconfig.json before proceeding.
{
"compilerOptions": {
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"strictBindCallApply": true,
"strictPropertyInitialization": true,
"noImplicitThis": true,
"useUnknownInCatchVariables": true,
"alwaysStrict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"exactOptionalPropertyTypes": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedIndexedAccess": true,
"noImplicitOverride": true,
"forceConsistentCasingInFileNames": true
}
}
Type System Idioms
Use unknown instead of any
// ❌ any disables type checking
function processPayload(payload: any) {
console.log(payload.id); // No error if id doesn't exist
}
// ✅ unknown forces narrowing
function processPayload(payload: unknown) {
if (typeof payload === 'object' && payload !== null && 'id' in payload) {
console.log(payload.id);
}
}
Discriminated Unions for state machines
// ❌ Optional properties lead to impossible states
type State = {
status: 'loading' | 'success' | 'error';
data?: string;
error?: Error;
};
// ✅ Discriminated union makes impossible states unrepresentable
type State =
| { status: 'loading' }
| { status: 'success'; data: string }
| { status: 'error'; error: Error };
Type narrowing with in and typeof
function handle(val: string | number) {
if (typeof val === 'string') {
// val is string
}
}
Satisfies operator for checking without widening
type Colors = 'red' | 'green' | 'blue';
type RGB = [number, number, number];
// ❌ Record widens the specific keys
const palette1: Record<Colors, RGB> = { red: [255, 0, 0], green: [0, 255, 0], blue: [0, 0, 255] };
// ✅ satisfies keeps exact type
const palette2 = { red: [255, 0, 0], green: [0, 255, 0], blue: [0, 0, 255] } satisfies Record<Colors, RGB>;
readonly everywhere
// ❌ Mutable arrays
function sum(numbers: number[]): number { ... }
// ✅ Readonly arrays
function sum(numbers: readonly number[]): number { ... }
Opaque/Nominal typing for domain primitives
type UserId = string & { readonly __brand: 'UserId' };
type OrderId = string & { readonly __brand: 'OrderId' };
function getUser(id: UserId): User { ... }
// ❌ Compile error — OrderId is not assignable to UserId
getUser(orderId);
// ✅ Explicit creation
const userId = 'u-123' as UserId;
getUser(userId);
Template literal types for string patterns
type EventName = `on${Capitalize<string>}`;
type Route = `/${string}`;
NoInfer<T> to prevent unwanted inference (TS 5.4+)
function createFSM<S extends string>(initial: S, transitions: Record<S, NoInfer<S>[]>) { ... }
Null Safety
- Enable
strictNullChecks (always).
- Optional Chaining (
?.) over explicit checks// ❌ Verbose
const city = user && user.address && user.address.city;
// ✅ Concise
const city = user?.address?.city;
- Nullish Coalescing (
??) over Logical OR (||)// ❌ Fails on 0 or ''
const count = input.count || 10;
// ✅ Only falls back on null/undefined
const count = input.count ?? 10;
- Explicit Resource Management (
using declarations — TypeScript 5.2+)
Requires lib: ["es2022"] or higher in tsconfig.json. Available in all Node.js 24 LTS projects.// ✅ Automatic cleanup — resource disposed when scope exits
{
using file = await openFile('data.csv');
// file is automatically closed when block exits, even on throw
}
Error Handling
Always throw Error instances, never primitives
// ❌ Loses stack trace, breaks instanceof checks
throw 'Something went wrong';
throw { message: 'fail' };
// ✅ Proper error with stack trace
throw new Error('Something went wrong');
Custom error classes for domain errors
export class NotFoundError extends Error {
constructor(public readonly resource: string, public readonly id: string) {
super(`${resource} not found: ${id}`);
this.name = 'NotFoundError';
}
}
Type-safe error narrowing
try {
await api.createUser(data);
} catch (err) {
// ❌ unsafe — err is unknown
console.log(err.message);
// ✅ narrowed
if (err instanceof NotFoundError) {
console.log(err.resource, err.id);
} else if (err instanceof Error) {
console.log(err.message);
}
}
Exhaustive error handling with Result<T, E> discriminated union
Use this when you want to make errors part of the return type (no throw/catch required).
// Define once, reuse everywhere
type Ok<T> = { ok: true; value: T };
type Err<E> = { ok: false; error: E };
type Result<T, E> = Ok<T> | Err<E>;
// Helper constructors eliminate boilerplate
const ok = <T>(value: T): Ok<T> => ({ ok: true, value });
const err = <E>(error: E): Err<E> => ({ ok: false, error });
// Usage — no try/catch, caller is forced to handle the error case
function divide(a: number, b: number): Result<number, string> {
if (b === 0) return err('Division by zero');
return ok(a / b);
}
const result = divide(10, 0);
if (!result.ok) {
console.error(result.error); // 'Division by zero'
} else {
console.log(result.value); // number
}
Async/Await
Always use async/await over raw Promises.
Use Promise.all for parallel operations.
// ❌ Sequential
const users = await getUsers();
const posts = await getPosts();
// ✅ Parallel
const [users, posts] = await Promise.all([getUsers(), getPosts()]);
Use Promise.allSettled when some can fail.
Avoid .then().catch() chains.
Abort long-running operations with AbortController
const controller = new AbortController();
const response = await fetch(url, { signal: controller.signal });
// Cancel if needed
controller.abort();
Never use async callbacks in Array.forEach
// ❌ forEach ignores returned promises — operations run detached
items.forEach(async (item) => {
await process(item);
});
// ✅ Use for...of for sequential
for (const item of items) {
await process(item);
}
// ✅ Use Promise.all for concurrent
await Promise.all(items.map(item => process(item)));
Handle timeouts with AbortSignal.timeout()
const response = await fetch(url, {
signal: AbortSignal.timeout(5000),
});
Runtime Validation at Boundaries
TypeScript types do not exist at runtime. Any data crossing an I/O boundary must be validated.
- Use Zod for all schema validation.
import { z } from 'zod';
const UserSchema = z.object({
id: z.string().uuid(),
name: z.string().min(2),
age: z.number().int().nonnegative(),
});
type User = z.infer<typeof UserSchema>;
function parseUser(data: unknown): User {
return UserSchema.parse(data);
}
For advanced Zod patterns (transforms, discriminated unions, branded types, error formatting), see references/zod-patterns.md.
Iteration and Collections
Use Map/Set over plain objects for dynamic keys
// ❌ Plain objects as maps — prototype pollution risk, string-only keys
const cache: Record<string, User> = {};
// ✅ Map — any key type, no prototype chain, O(1) has/get/set
const cache = new Map<string, User>();
Use structuredClone() for deep copies (not JSON round-trip)
// ❌ Lossy — drops undefined, functions, Date objects, BigInt
const copy = JSON.parse(JSON.stringify(original));
// ✅ Handles circular refs, Date, RegExp, Map, Set, ArrayBuffer
const copy = structuredClone(original);
Prefer immutable array methods (ES2023+)
// ❌ Mutates original array
const sorted = arr.sort((a, b) => a - b);
const reversed = arr.reverse();
// ✅ Returns new array, original unchanged
const sorted = arr.toSorted((a, b) => a - b);
const reversed = arr.toReversed();
const withReplacement = arr.with(2, 'new');
Use Object.groupBy() for grouping (ES2024)
Use Set for O(1) lookups instead of Array.includes in loops
Centralized HTTP Client
Never use raw fetch spread throughout the codebase. Centralize it to handle tokens, retries, and errors.
Testability requirement: Always define an interface first. The concrete class implements it.
This lets tests inject a FakeHttpClient without network calls.
// ✅ Define interface first — enables test doubles (architectural rule: I/O isolation)
export interface HttpClient {
get<T>(path: string, schema: z.ZodType<T>): Promise<T>;
post<T>(path: string, body: unknown, schema: z.ZodType<T>): Promise<T>;
delete(path: string): Promise<void>;
}
// ✅ Production implementation
export class ApiClient implements HttpClient {
constructor(private readonly baseUrl: string) {}
async get<T>(path: string, schema: z.ZodType<T>): Promise<T> {
const res = await fetch(`${this.baseUrl}${path}`, {
signal: AbortSignal.timeout(10_000),
});
if (!res.ok) throw new ApiError(res.status, res.statusText);
const data: unknown = await res.json();
return schema.parse(data);
}
async post<T>(path: string, body: unknown, schema: z.ZodType<T>): Promise<T> {
const res = await fetch(`${this.baseUrl}${path}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
signal: AbortSignal.timeout(10_000),
});
if (!res.ok) throw new ApiError(res.status, res.statusText);
const data: unknown = await res.json();
return schema.parse(data);
}
async delete(path: string): Promise<void> {
const res = await fetch(`${this.baseUrl}${path}`, {
method: 'DELETE',
signal: AbortSignal.timeout(10_000),
});
if (!res.ok) throw new ApiError(res.status, res.statusText);
}
}
// ✅ Test double — use in unit tests, no network required
export class FakeHttpClient implements HttpClient {
readonly calls: { method: string; path: string }[] = [];
private responses = new Map<string, unknown>();
enqueue(path: string, response: unknown): void {
this.responses.set(path, response);
}
async get<T>(path: string, schema: z.ZodType<T>): Promise<T> {
this.calls.push({ method: 'GET', path });
return schema.parse(this.responses.get(path));
}
async post<T>(path: string, body: unknown, schema: z.ZodType<T>): Promise<T> {
this.calls.push({ method: 'POST', path });
return schema.parse(this.responses.get(path));
}
async delete(path: string): Promise<void> {
this.calls.push({ method: 'DELETE', path });
}
}
Idiomatic Patterns
Parameter object over positional arguments
// ❌ Positional — error-prone, order-sensitive, boolean traps
function createUser(name: string, email: string, isAdmin: boolean, isActive: boolean) {}
// ✅ Named parameters — self-documenting, order-independent
interface CreateUserParams {
name: string;
email: string;
isAdmin: boolean;
isActive: boolean;
}
function createUser(params: CreateUserParams) {}
Branded/Opaque types for domain primitives — see Type System Idioms §6. Never pass bare string or number for domain IDs.
Discriminated unions over inheritance — prefer union types with a type or kind discriminant over class hierarchies. Invalid states become compile errors.
Parse, don't validate — convert raw input into typed, validated domain objects at the boundary. Downstream code works with the typed form and never re-validates.
// ❌ Validate at every call site
function processOrder(orderId: string) {
if (!isValidUuid(orderId)) throw new Error('Invalid');
// ...
}
// ✅ Parse at boundary, use branded type everywhere else
const orderId = OrderIdSchema.parse(rawInput); // throws once at entry
processOrder(orderId); // OrderId is always valid
Early returns to reduce nesting — use guard clauses instead of nested if/else.
// ❌ Deep nesting
function handle(req: Request) {
if (req.auth) {
if (req.auth.isValid) {
if (req.body) {
return process(req.body);
}
}
}
}
// ✅ Guard clauses
function handle(req: Request) {
if (!req.auth) return unauthorized();
if (!req.auth.isValid) return forbidden();
if (!req.body) return badRequest();
return process(req.body);
}
Keep function complexity low (cyclomatic complexity < 10)
- Functions exceeding this threshold must be decomposed
- Common signal: if explaining what a function does requires the word "and", split it
Module and Export Patterns
- Avoid
export default. Use named exports for better refactoring and intellisense.
- Use barrel files (
index.ts) sparingly. They can cause circular dependencies.
- Use type-only imports.
// ✅ Ensures type is erased at runtime
import type { User } from './types';
import { parseUser } from './parser';
ESLint Suppression Policy
NEVER suppress these rules — they signal structural problems that must be fixed:
| Rule |
What It Signals |
What To Do Instead |
@typescript-eslint/no-explicit-any |
Type safety disabled |
Use unknown and narrow |
@typescript-eslint/no-floating-promises |
Unhandled async operation |
Add await or void |
@typescript-eslint/no-unsafe-assignment |
Unsafe type flow |
Type the source properly |
@typescript-eslint/no-unnecessary-condition |
Dead code or logic bug |
Remove the condition |
complexity |
Function too complex |
Decompose into smaller functions |
Acceptable suppressions (with mandatory // SUPPRESS: comment):
| Rule |
When Acceptable |
@typescript-eslint/no-non-null-assertion |
After runtime validation proves non-null |
@typescript-eslint/ban-ts-comment |
@ts-expect-error with explanation (never @ts-ignore) |
no-console |
In CLI tools or development scripts |
Rule of thumb: If you're about to write // eslint-disable, stop and ask: "Am I suppressing a real design problem?" If yes, fix the design.
Testing
Use Vitest over Jest. It's faster, ESM-native, and requires zero config for TS.
AAA Pattern (Arrange, Act, Assert).
Test behavior, not implementation.
Test async errors by type, not message
Use vi.spyOn for interaction verification
Use satisfies for type-checked test fixtures
const mockUser = { id: '1', name: 'Test' } satisfies Partial<User>;
Test coverage is non-negotiable for new code:
- Every new exported function and class method MUST have at least one test
- Every new branch (
if/else, switch arm, error path) MUST be exercised
- When modifying existing code, add tests for the modified paths if none exist
- Never leave a function untested with the intent to "add tests later"
- Use
@vitest/coverage-v8 to verify coverage locally before committing
# Quick coverage check
vitest run --coverage
# Coverage with thresholds
vitest run --coverage --coverage.thresholds.lines=80
Test double selection — choose the right tool:
| Approach |
When to Use |
| Hand-written fake (implement interface) |
Simple interface, few methods, need stateful behavior |
vi.fn() / vi.spyOn() |
Verify call counts, argument matching |
msw (Mock Service Worker) |
HTTP boundary mocking — intercepts at network level |
Parameterized it.each / test.each |
Same logic, multiple input/output pairs |
Snapshot (expect().toMatchSnapshot()) |
Large outputs — JSON responses, CLI output |
Prefer hand-written fakes for repository interfaces — they are simpler to debug and don't couple tests to implementation details. Use vi.fn() when you genuinely need interaction verification.
Feedback Loop — Development Workflow
tsc --noEmit is the TypeScript equivalent of Rust's cargo check — type-checks without producing output. It is the fastest possible feedback during TDD cycles.
| Phase |
Command |
Purpose |
| TDD / rapid iteration |
tsc --noEmit |
Type-check only, no emit — fastest loop |
| Pre-commit |
eslint . |
Static analysis — must pass with zero warnings |
| Pre-commit |
prettier --write . |
Formatting — non-negotiable, always run |
| Pre-commit |
vitest run |
Unit tests — must all pass |
| Coverage verification |
vitest run --coverage |
Verify before merging |
| Unused dep audit |
knip |
Run before releases |
Rules:
- Never run a full
tsc build during TDD cycles — tsc --noEmit is sufficient and significantly faster.
eslint . must pass with zero warnings before any commit. Warnings are treated as errors.
prettier --write . is non-negotiable — all code must be formatted before committing.
- If
knip reports unused exports or dependencies, remove them before the release.
Documentation
Document all exported items:
- Every exported function, class, type, and interface MUST have a JSDoc comment
- At minimum: one-line summary. For complex items: summary +
@param + @returns + @throws
- Document the why for non-obvious design decisions, not the what
// ❌ Undocumented exported function
export function parseUserToken(token: string): UserId { ... }
// ✅ Documented
/**
* Parses and validates a signed user token, returning the extracted UserId.
*
* @param token - JWT signed token from the Authorization header
* @returns Validated UserId branded type
* @throws {InvalidTokenError} if the token is expired, malformed, or signature invalid
*/
export function parseUserToken(token: string): UserId { ... }
Dependency Management
- Minimize dependency count — each dependency is an attack surface and bundle-size cost
- Audit regularly — run
npm audit or pnpm audit in CI
- Pin major versions in
package.json with ^ for libraries (^3.0.0)
- Always commit the lockfile (
package-lock.json or pnpm-lock.yaml) — for both apps and libraries
- Check for unused dependencies with
knip before releases
- Prefer native APIs over packages when the native alternative is stable:
crypto.randomUUID() over uuid package
structuredClone() over lodash deep clone
Array.toSorted() over lodash sort
Object.groupBy() over lodash groupBy
- Never import entire utility libraries when only one function is needed — use subpath imports or native alternatives
For the full curated dependency list with versions, see references/recommended-dependencies.md.
Configuration and Environment
Never scatter process.env calls throughout the codebase
// ❌ Scattered, typo-prone, no validation
const port = process.env.PORT || '3000';
const dbUrl = process.env.DATABASE_URL;
// ✅ Centralized, validated at startup
import { z } from 'zod';
const EnvSchema = z.object({
PORT: z.coerce.number().default(3000),
DATABASE_URL: z.string().url(),
NODE_ENV: z.enum(['development', 'production', 'test']).default('development'),
});
export const env = EnvSchema.parse(process.env);
Fail fast on missing required config at boot, not at first use
Safety, Security, and Performance
For type coercion traps, prototype pollution, scope bugs, security vulnerabilities, collection pitfalls, and performance invariants, see references/ts-patterns-and-anti-patterns.md. Load it before writing any code handling user input, async operations, or I/O.
For performance patterns, see perf-optimization skill.
Related
- Error Handling Principles @.agents/rules/error-handling-principles.md
- Security Principles @.agents/rules/security-principles.md
- Architectural Patterns — Testability-First Design @.agents/rules/architectural-pattern.md
- Concurrency and Threading Principles @.agents/rules/concurrency-and-threading-principles.md
- Core Design Principles @.agents/rules/core-design-principles.md
- Performance Optimization Principles @.agents/rules/performance-optimization-principles.md
- Resource and Memory Management Principles @.agents/rules/resources-and-memory-management-principles.md
- Security Mandate @.agents/rules/security-mandate.md
- Code Idioms and Conventions @.agents/rules/code-idioms-and-conventions.md
- Testing Strategy @.agents/rules/testing-strategy.md
- Logging and Observability Mandate @.agents/rules/logging-and-observability-mandate.md
- Dependency Management Principles @.agents/rules/dependency-management-principles.md
- Logging Implementation @.agents/skills/logging-implementation/SKILL.md
- Vue Idioms @.agents/skills/vue-idioms/SKILL.md
- React Idioms @.agents/skills/react-idioms/SKILL.md
- Hono Idioms @.agents/skills/hono-idioms/SKILL.md
- Next.js Idioms @.agents/skills/nextjs-idioms/SKILL.md
- Angular Idioms @.agents/skills/angular-idioms/SKILL.md
- Testability Patterns @.agents/skills/testability-patterns/SKILL.md
1---2name: typescript-idioms-23description: TypeScript strict mode, type narrowing, Zod validation, vitest, ESLint flat config.4---56## Core Philosophy7TypeScript's type system is your documentation, your test, and your specification — all at once. Make the type system encode the invariants of your domain so that invalid states are unrepresentable. Lean into the compiler.89> **Scope:** This file covers TypeScript-specific *type system and language idioms*. For framework-specific patterns, see the respective idiom skill (Vue, React, Angular, Next.js, Hono). For file layout, see `references/project-structure.md`. For detailed safety, SAST patterns, and performance patterns, see `references/ts-patterns-and-anti-patterns.md`. For quality commands, see `@.agents/rules/code-idioms-and-conventions.md`. For logging library, see `@.agents/skills/logging-implementation/SKILL.md`.1011> **Loading guards:**12> - **Plain JavaScript (no `tsconfig.json`):** load `@.agents/skills/javascript-idioms/SKILL.md` instead — this skill assumes strict-mode TS.13> - **Hono backend:** `hono` has no repo-level marker file, so it is not auto-detected. If `hono` appears in `package.json` dependencies, **co-load `@.agents/skills/hono-idioms/SKILL.md`** alongside this skill.14> - **Test-file naming diverges by framework:** see `references/project-structure.md` § Test Organization for the reconciliation rule before creating test files.1516## When to Load References1718> Load these **before** writing code in the matching context — not after.1920| Situation | Reference to Load |21|---|---|22| Starting a new project or setting up file layout | `references/project-structure.md` |23| Choosing packages, tsconfig template, or vitest config | `references/recommended-dependencies.md` |24| Writing code that handles user input, async operations, or I/O | `references/ts-patterns-and-anti-patterns.md` |25| Defining Zod schemas or validating API/env boundaries | `references/zod-patterns.md` |2627## Toolchain and Runtime28- Default to latest Node.js LTS. As of July 2026, Node.js 24 LTS with TypeScript 5.8+29- ESM over CJS for all new projects30- `tsx` for development execution (replaces ts-node)31- Key version milestones: TS 5.0+ decorators, TS 5.4+ NoInfer, TS 5.5+ inferred type predicates3233## Strict Mode — Non-Negotiable34All TypeScript projects MUST have strict mode enabled. If a project does not have these settings, fix `tsconfig.json` before proceeding.3536```json37{38 "compilerOptions": {39 "strict": true,40 "noImplicitAny": true,41 "strictNullChecks": true,42 "strictFunctionTypes": true,43 "strictBindCallApply": true,44 "strictPropertyInitialization": true,45 "noImplicitThis": true,46 "useUnknownInCatchVariables": true,47 "alwaysStrict": true,48 "noUnusedLocals": true,49 "noUnusedParameters": true,50 "exactOptionalPropertyTypes": true,51 "noImplicitReturns": true,52 "noFallthroughCasesInSwitch": true,53 "noUncheckedIndexedAccess": true,54 "noImplicitOverride": true,55 "forceConsistentCasingInFileNames": true56 }57}58```5960## Type System Idioms61621. **Use `unknown` instead of `any`**63 ```typescript64 // ❌ any disables type checking65 function processPayload(payload: any) {66 console.log(payload.id); // No error if id doesn't exist67 }6869 // ✅ unknown forces narrowing70 function processPayload(payload: unknown) {71 if (typeof payload === 'object' && payload !== null && 'id' in payload) {72 console.log(payload.id);73 }74 }75 ```76772. **Discriminated Unions for state machines**78 ```typescript79 // ❌ Optional properties lead to impossible states80 type State = {81 status: 'loading' | 'success' | 'error';82 data?: string;83 error?: Error;84 };8586 // ✅ Discriminated union makes impossible states unrepresentable87 type State = 88 | { status: 'loading' }89 | { status: 'success'; data: string }90 | { status: 'error'; error: Error };91 ```92933. **Type narrowing with `in` and `typeof`**94 ```typescript95 function handle(val: string | number) {96 if (typeof val === 'string') {97 // val is string98 }99 }100 ```1011024. **Satisfies operator for checking without widening**103 ```typescript104 type Colors = 'red' | 'green' | 'blue';105 type RGB = [number, number, number];106 107 // ❌ Record widens the specific keys108 const palette1: Record<Colors, RGB> = { red: [255, 0, 0], green: [0, 255, 0], blue: [0, 0, 255] };109 110 // ✅ satisfies keeps exact type111 const palette2 = { red: [255, 0, 0], green: [0, 255, 0], blue: [0, 0, 255] } satisfies Record<Colors, RGB>;112 ```1131145. **`readonly` everywhere**115 ```typescript116 // ❌ Mutable arrays117 function sum(numbers: number[]): number { ... }118 119 // ✅ Readonly arrays120 function sum(numbers: readonly number[]): number { ... }121 ```1221236. **Opaque/Nominal typing for domain primitives**124 ```typescript125 type UserId = string & { readonly __brand: 'UserId' };126 type OrderId = string & { readonly __brand: 'OrderId' };127 128 function getUser(id: UserId): User { ... }129 130 // ❌ Compile error — OrderId is not assignable to UserId131 getUser(orderId);132 133 // ✅ Explicit creation134 const userId = 'u-123' as UserId;135 getUser(userId);136 ```1371387. **Template literal types for string patterns**139 ```typescript140 type EventName = `on${Capitalize<string>}`;141 type Route = `/${string}`;142 ```1431448. **`NoInfer<T>` to prevent unwanted inference (TS 5.4+)**145 ```typescript146 function createFSM<S extends string>(initial: S, transitions: Record<S, NoInfer<S>[]>) { ... }147 ```148149## Null Safety1501. **Enable `strictNullChecks`** (always).1512. **Optional Chaining (`?.`) over explicit checks**152 ```typescript153 // ❌ Verbose154 const city = user && user.address && user.address.city;155 156 // ✅ Concise157 const city = user?.address?.city;158 ```1593. **Nullish Coalescing (`??`) over Logical OR (`||`)**160 ```typescript161 // ❌ Fails on 0 or ''162 const count = input.count || 10;163 164 // ✅ Only falls back on null/undefined165 const count = input.count ?? 10;166 ```1674. **Explicit Resource Management (`using` declarations — TypeScript 5.2+)**168 Requires `lib: ["es2022"]` or higher in `tsconfig.json`. Available in all Node.js 24 LTS projects.169 ```typescript170 // ✅ Automatic cleanup — resource disposed when scope exits171 {172 using file = await openFile('data.csv');173 // file is automatically closed when block exits, even on throw174 }175 ```176177## Error Handling1781. **Always throw Error instances, never primitives**179 ```typescript180 // ❌ Loses stack trace, breaks instanceof checks181 throw 'Something went wrong';182 throw { message: 'fail' };183 184 // ✅ Proper error with stack trace185 throw new Error('Something went wrong');186 ```1871882. **Custom error classes for domain errors**189 ```typescript190 export class NotFoundError extends Error {191 constructor(public readonly resource: string, public readonly id: string) {192 super(`${resource} not found: ${id}`);193 this.name = 'NotFoundError';194 }195 }196 ```1971983. **Type-safe error narrowing**199 ```typescript200 try {201 await api.createUser(data);202 } catch (err) {203 // ❌ unsafe — err is unknown204 console.log(err.message);205 206 // ✅ narrowed207 if (err instanceof NotFoundError) {208 console.log(err.resource, err.id);209 } else if (err instanceof Error) {210 console.log(err.message);211 }212 }213 ```2142154. **Exhaustive error handling with `Result<T, E>` discriminated union**216217 Use this when you want to make errors part of the return type (no throw/catch required).218219 ```typescript220 // Define once, reuse everywhere221 type Ok<T> = { ok: true; value: T };222 type Err<E> = { ok: false; error: E };223 type Result<T, E> = Ok<T> | Err<E>;224225 // Helper constructors eliminate boilerplate226 const ok = <T>(value: T): Ok<T> => ({ ok: true, value });227 const err = <E>(error: E): Err<E> => ({ ok: false, error });228229 // Usage — no try/catch, caller is forced to handle the error case230 function divide(a: number, b: number): Result<number, string> {231 if (b === 0) return err('Division by zero');232 return ok(a / b);233 }234235 const result = divide(10, 0);236 if (!result.ok) {237 console.error(result.error); // 'Division by zero'238 } else {239 console.log(result.value); // number240 }241 ```242243## Async/Await2441. **Always use async/await over raw Promises.**2452. **Use `Promise.all` for parallel operations.**246 ```typescript247 // ❌ Sequential248 const users = await getUsers();249 const posts = await getPosts();250 251 // ✅ Parallel252 const [users, posts] = await Promise.all([getUsers(), getPosts()]);253 ```2543. **Use `Promise.allSettled` when some can fail.**2554. **Avoid `.then().catch()` chains.**2565. **Abort long-running operations with AbortController**257 ```typescript258 const controller = new AbortController();259 const response = await fetch(url, { signal: controller.signal });260 // Cancel if needed261 controller.abort();262 ```2632646. **Never use async callbacks in Array.forEach**265 ```typescript266 // ❌ forEach ignores returned promises — operations run detached267 items.forEach(async (item) => {268 await process(item);269 });270 271 // ✅ Use for...of for sequential272 for (const item of items) {273 await process(item);274 }275 276 // ✅ Use Promise.all for concurrent277 await Promise.all(items.map(item => process(item)));278 ```2792807. **Handle timeouts with AbortSignal.timeout()**281 ```typescript282 const response = await fetch(url, {283 signal: AbortSignal.timeout(5000),284 });285 ```286287## Runtime Validation at Boundaries288TypeScript types do not exist at runtime. Any data crossing an I/O boundary must be validated.2891. **Use Zod for all schema validation.**290 ```typescript291 import { z } from 'zod';292 293 const UserSchema = z.object({294 id: z.string().uuid(),295 name: z.string().min(2),296 age: z.number().int().nonnegative(),297 });298 299 type User = z.infer<typeof UserSchema>;300 301 function parseUser(data: unknown): User {302 return UserSchema.parse(data);303 }304 ```305> For advanced Zod patterns (transforms, discriminated unions, branded types, error formatting), see `references/zod-patterns.md`.306307## Iteration and Collections3081. **Use `Map`/`Set` over plain objects for dynamic keys**309 ```typescript310 // ❌ Plain objects as maps — prototype pollution risk, string-only keys311 const cache: Record<string, User> = {};312 313 // ✅ Map — any key type, no prototype chain, O(1) has/get/set314 const cache = new Map<string, User>();315 ```3163172. **Use `structuredClone()` for deep copies (not JSON round-trip)**318 ```typescript319 // ❌ Lossy — drops undefined, functions, Date objects, BigInt320 const copy = JSON.parse(JSON.stringify(original));321 322 // ✅ Handles circular refs, Date, RegExp, Map, Set, ArrayBuffer323 const copy = structuredClone(original);324 ```3253263. **Prefer immutable array methods (ES2023+)**327 ```typescript328 // ❌ Mutates original array329 const sorted = arr.sort((a, b) => a - b);330 const reversed = arr.reverse();331 332 // ✅ Returns new array, original unchanged333 const sorted = arr.toSorted((a, b) => a - b);334 const reversed = arr.toReversed();335 const withReplacement = arr.with(2, 'new');336 ```3373384. **Use `Object.groupBy()` for grouping (ES2024)**3395. **Use `Set` for O(1) lookups instead of Array.includes in loops**340341## Centralized HTTP Client342Never use raw `fetch` spread throughout the codebase. Centralize it to handle tokens, retries, and errors.343344> **Testability requirement:** Always define an interface first. The concrete class implements it.345> This lets tests inject a `FakeHttpClient` without network calls.346347```typescript348// ✅ Define interface first — enables test doubles (architectural rule: I/O isolation)349export interface HttpClient {350 get<T>(path: string, schema: z.ZodType<T>): Promise<T>;351 post<T>(path: string, body: unknown, schema: z.ZodType<T>): Promise<T>;352 delete(path: string): Promise<void>;353}354355// ✅ Production implementation356export class ApiClient implements HttpClient {357 constructor(private readonly baseUrl: string) {}358359 async get<T>(path: string, schema: z.ZodType<T>): Promise<T> {360 const res = await fetch(`${this.baseUrl}${path}`, {361 signal: AbortSignal.timeout(10_000),362 });363 if (!res.ok) throw new ApiError(res.status, res.statusText);364 const data: unknown = await res.json();365 return schema.parse(data);366 }367368 async post<T>(path: string, body: unknown, schema: z.ZodType<T>): Promise<T> {369 const res = await fetch(`${this.baseUrl}${path}`, {370 method: 'POST',371 headers: { 'Content-Type': 'application/json' },372 body: JSON.stringify(body),373 signal: AbortSignal.timeout(10_000),374 });375 if (!res.ok) throw new ApiError(res.status, res.statusText);376 const data: unknown = await res.json();377 return schema.parse(data);378 }379380 async delete(path: string): Promise<void> {381 const res = await fetch(`${this.baseUrl}${path}`, {382 method: 'DELETE',383 signal: AbortSignal.timeout(10_000),384 });385 if (!res.ok) throw new ApiError(res.status, res.statusText);386 }387}388389// ✅ Test double — use in unit tests, no network required390export class FakeHttpClient implements HttpClient {391 readonly calls: { method: string; path: string }[] = [];392 private responses = new Map<string, unknown>();393394 enqueue(path: string, response: unknown): void {395 this.responses.set(path, response);396 }397398 async get<T>(path: string, schema: z.ZodType<T>): Promise<T> {399 this.calls.push({ method: 'GET', path });400 return schema.parse(this.responses.get(path));401 }402403 async post<T>(path: string, body: unknown, schema: z.ZodType<T>): Promise<T> {404 this.calls.push({ method: 'POST', path });405 return schema.parse(this.responses.get(path));406 }407408 async delete(path: string): Promise<void> {409 this.calls.push({ method: 'DELETE', path });410 }411}412```413414## Idiomatic Patterns4154161. **Parameter object over positional arguments**417 ```typescript418 // ❌ Positional — error-prone, order-sensitive, boolean traps419 function createUser(name: string, email: string, isAdmin: boolean, isActive: boolean) {}420421 // ✅ Named parameters — self-documenting, order-independent422 interface CreateUserParams {423 name: string;424 email: string;425 isAdmin: boolean;426 isActive: boolean;427 }428 function createUser(params: CreateUserParams) {}429 ```4304312. **Branded/Opaque types for domain primitives** — see Type System Idioms §6. Never pass bare `string` or `number` for domain IDs.4324333. **Discriminated unions over inheritance** — prefer union types with a `type` or `kind` discriminant over class hierarchies. Invalid states become compile errors.4344354. **Parse, don't validate** — convert raw input into typed, validated domain objects at the boundary. Downstream code works with the typed form and never re-validates.436 ```typescript437 // ❌ Validate at every call site438 function processOrder(orderId: string) {439 if (!isValidUuid(orderId)) throw new Error('Invalid');440 // ...441 }442443 // ✅ Parse at boundary, use branded type everywhere else444 const orderId = OrderIdSchema.parse(rawInput); // throws once at entry445 processOrder(orderId); // OrderId is always valid446 ```4474485. **Early returns to reduce nesting** — use guard clauses instead of nested `if/else`.449 ```typescript450 // ❌ Deep nesting451 function handle(req: Request) {452 if (req.auth) {453 if (req.auth.isValid) {454 if (req.body) {455 return process(req.body);456 }457 }458 }459 }460461 // ✅ Guard clauses462 function handle(req: Request) {463 if (!req.auth) return unauthorized();464 if (!req.auth.isValid) return forbidden();465 if (!req.body) return badRequest();466 return process(req.body);467 }468 ```4694706. **Keep function complexity low (cyclomatic complexity < 10)**471 - Functions exceeding this threshold must be decomposed472 - Common signal: if explaining what a function does requires the word "and", split it473474## Module and Export Patterns4751. **Avoid `export default`.** Use named exports for better refactoring and intellisense.4762. **Use barrel files (`index.ts`) sparingly.** They can cause circular dependencies.4773. **Use type-only imports.**478 ```typescript479 // ✅ Ensures type is erased at runtime480 import type { User } from './types';481 import { parseUser } from './parser';482 ```483484## ESLint Suppression Policy485486**NEVER suppress these rules — they signal structural problems that must be fixed:**487488| Rule | What It Signals | What To Do Instead |489|---|---|---|490| `@typescript-eslint/no-explicit-any` | Type safety disabled | Use `unknown` and narrow |491| `@typescript-eslint/no-floating-promises` | Unhandled async operation | Add `await` or `void` |492| `@typescript-eslint/no-unsafe-assignment` | Unsafe type flow | Type the source properly |493| `@typescript-eslint/no-unnecessary-condition` | Dead code or logic bug | Remove the condition |494| `complexity` | Function too complex | Decompose into smaller functions |495496**Acceptable suppressions (with mandatory `// SUPPRESS:` comment):**497498| Rule | When Acceptable |499|---|---|500| `@typescript-eslint/no-non-null-assertion` | After runtime validation proves non-null |501| `@typescript-eslint/ban-ts-comment` | `@ts-expect-error` with explanation (never `@ts-ignore`) |502| `no-console` | In CLI tools or development scripts |503504**Rule of thumb:** If you're about to write `// eslint-disable`, stop and ask: "Am I suppressing a real design problem?" If yes, fix the design.505506## Testing5071. **Use Vitest over Jest.** It's faster, ESM-native, and requires zero config for TS.5082. **AAA Pattern (Arrange, Act, Assert).**5093. **Test behavior, not implementation.**5104. **Test async errors by type, not message**5115. **Use `vi.spyOn` for interaction verification**5126. **Use `satisfies` for type-checked test fixtures**513 ```typescript514 const mockUser = { id: '1', name: 'Test' } satisfies Partial<User>;515 ```5165177. **Test coverage is non-negotiable for new code:**518 - Every new exported function and class method MUST have at least one test519 - Every new branch (`if`/`else`, `switch` arm, error path) MUST be exercised520 - When modifying existing code, add tests for the modified paths if none exist521 - Never leave a function untested with the intent to "add tests later"522 - Use `@vitest/coverage-v8` to verify coverage locally before committing523 ```bash524 # Quick coverage check525 vitest run --coverage526 # Coverage with thresholds527 vitest run --coverage --coverage.thresholds.lines=80528 ```5295308. **Test double selection — choose the right tool:**531532 | Approach | When to Use |533 |---|---|534 | Hand-written fake (implement interface) | Simple interface, few methods, need stateful behavior |535 | `vi.fn()` / `vi.spyOn()` | Verify call counts, argument matching |536 | `msw` (Mock Service Worker) | HTTP boundary mocking — intercepts at network level |537 | Parameterized `it.each` / `test.each` | Same logic, multiple input/output pairs |538 | Snapshot (`expect().toMatchSnapshot()`) | Large outputs — JSON responses, CLI output |539540 > **Prefer hand-written fakes** for repository interfaces — they are simpler to debug and don't couple tests to implementation details. Use `vi.fn()` when you genuinely need interaction verification.541542## Feedback Loop — Development Workflow543544> `tsc --noEmit` is the TypeScript equivalent of Rust's `cargo check` — type-checks without producing output. It is the fastest possible feedback during TDD cycles.545546| Phase | Command | Purpose |547|---|---|---|548| TDD / rapid iteration | `tsc --noEmit` | Type-check only, no emit — fastest loop |549| Pre-commit | `eslint .` | Static analysis — must pass with **zero warnings** |550| Pre-commit | `prettier --write .` | Formatting — non-negotiable, always run |551| Pre-commit | `vitest run` | Unit tests — must all pass |552| Coverage verification | `vitest run --coverage` | Verify before merging |553| Unused dep audit | `knip` | Run before releases |554555**Rules:**556- Never run a full `tsc` build during TDD cycles — `tsc --noEmit` is sufficient and significantly faster.557- `eslint .` must pass with **zero warnings** before any commit. Warnings are treated as errors.558- `prettier --write .` is non-negotiable — all code must be formatted before committing.559- If `knip` reports unused exports or dependencies, remove them before the release.560561## Documentation562563**Document all exported items:**564- Every exported function, class, type, and interface MUST have a JSDoc comment565- At minimum: one-line summary. For complex items: summary + `@param` + `@returns` + `@throws`566- Document the **why** for non-obvious design decisions, not the **what**567568```typescript569// ❌ Undocumented exported function570export function parseUserToken(token: string): UserId { ... }571572// ✅ Documented573/**574 * Parses and validates a signed user token, returning the extracted UserId.575 *576 * @param token - JWT signed token from the Authorization header577 * @returns Validated UserId branded type578 * @throws {InvalidTokenError} if the token is expired, malformed, or signature invalid579 */580export function parseUserToken(token: string): UserId { ... }581```582583## Dependency Management5845851. **Minimize dependency count** — each dependency is an attack surface and bundle-size cost5862. **Audit regularly** — run `npm audit` or `pnpm audit` in CI5873. **Pin major versions** in `package.json` with `^` for libraries (`^3.0.0`)5884. **Always commit the lockfile** (`package-lock.json` or `pnpm-lock.yaml`) — for both apps and libraries5895. **Check for unused dependencies** with `knip` before releases5906. **Prefer native APIs** over packages when the native alternative is stable:591 - `crypto.randomUUID()` over `uuid` package592 - `structuredClone()` over lodash deep clone593 - `Array.toSorted()` over lodash sort594 - `Object.groupBy()` over lodash groupBy5957. **Never import entire utility libraries** when only one function is needed — use subpath imports or native alternatives596597> For the full curated dependency list with versions, see `references/recommended-dependencies.md`.598599## Configuration and Environment6001. **Never scatter `process.env` calls throughout the codebase**601 ```typescript602 // ❌ Scattered, typo-prone, no validation603 const port = process.env.PORT || '3000';604 const dbUrl = process.env.DATABASE_URL;605 606 // ✅ Centralized, validated at startup607 import { z } from 'zod';608 const EnvSchema = z.object({609 PORT: z.coerce.number().default(3000),610 DATABASE_URL: z.string().url(),611 NODE_ENV: z.enum(['development', 'production', 'test']).default('development'),612 });613 export const env = EnvSchema.parse(process.env);614 ```6156162. **Fail fast on missing required config at boot, not at first use**617618## Safety, Security, and Performance619> For type coercion traps, prototype pollution, scope bugs, security vulnerabilities, collection pitfalls, and performance invariants, see `references/ts-patterns-and-anti-patterns.md`. Load it before writing any code handling user input, async operations, or I/O.620>621> For performance patterns, see `perf-optimization` skill.622623## Related624- Error Handling Principles @.agents/rules/error-handling-principles.md625- Security Principles @.agents/rules/security-principles.md626- Architectural Patterns — Testability-First Design @.agents/rules/architectural-pattern.md627- Concurrency and Threading Principles @.agents/rules/concurrency-and-threading-principles.md628- Core Design Principles @.agents/rules/core-design-principles.md629- Performance Optimization Principles @.agents/rules/performance-optimization-principles.md630- Resource and Memory Management Principles @.agents/rules/resources-and-memory-management-principles.md631- Security Mandate @.agents/rules/security-mandate.md632- Code Idioms and Conventions @.agents/rules/code-idioms-and-conventions.md633- Testing Strategy @.agents/rules/testing-strategy.md634- Logging and Observability Mandate @.agents/rules/logging-and-observability-mandate.md635- Dependency Management Principles @.agents/rules/dependency-management-principles.md636- Logging Implementation @.agents/skills/logging-implementation/SKILL.md637- Vue Idioms @.agents/skills/vue-idioms/SKILL.md638- React Idioms @.agents/skills/react-idioms/SKILL.md639- Hono Idioms @.agents/skills/hono-idioms/SKILL.md640- Next.js Idioms @.agents/skills/nextjs-idioms/SKILL.md641- Angular Idioms @.agents/skills/angular-idioms/SKILL.md642- Testability Patterns @.agents/skills/testability-patterns/SKILL.md