Typescript Rules
ASecurityTeam conventions for TypeScript code: named functions with the function keyword, inline arrow callbacks, Array<T>, method signatures in object types, closed string sets as const objects instead of enums, unknown instead of any, the ~/ import alias, JSDoc comments that explain only a non-obvious why, and error handling: [error, data] Result tuples, the ServiceError template, API client functions, retries and timeouts. Use when writing, fixing or reviewing TypeScript or TSX. Background knowledg...
- 2 stars
- 0 votes
- 0 copies
- 2 views
- Added November 17, 2026
Works with
Security analysis
100/100Pro scans all 2 files and shows the line behind each finding
npx -y skills add JanSzewczyk/claude-plugins --skill typescript-rules --agent claude-codeAre you the author of Typescript Rules?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/janszewczyk-typescript-rules)---
name: typescript-rules
description: "Team conventions for TypeScript code: named functions with the function keyword, inline arrow callbacks, Array<T>, method signatures in object types, closed string sets as const objects instead of enums, unknown instead of any, the ~/ import alias, JSDoc comments that explain only a non-obvious why, and error handling: [error, data] Result tuples, the ServiceError template, API client functions, retries and timeouts. Use when writing, fixing or reviewing TypeScript or TSX. Background knowledge that agents preload; not a command."
user-invocable: false
---
<!-- generated by knowledge.mjs from 23 note(s) (sha256 80fb7c2d3163); edit the notes in knowledge/, then run build -->
# TypeScript rules
Apply these rules to every TypeScript file you write or review. React rules are in `react-rules`, Next.js rules in `nextjs-rules`. The first section is always in force; open a rule from the table when the task touches it.
## Always apply (critical, high)
### Cap retries and wait a jittered, exponentially growing delay between them
_high · any_
**Rule.** Allow a fixed maximum number of attempts (three is the default), wait `base × 2^attempt` capped at a ceiling before each retry, and randomise that wait. When the server sends `Retry-After`, wait that long instead, within the same ceiling. After the last attempt, return the final error.
**Why.** Unbounded or immediate retries turn one struggling dependency into an outage: every client hammers it in synchronised waves, and a request that can never succeed holds its caller forever.
### Retry only transient failures of idempotent operations
_high · any_
**Rule.** Retry a call only when its failure is transient (timeout, connection refused, rate limited, upstream unavailable) and the operation is idempotent: a read, or a write that carries an idempotency key. Return every other failure to the caller on the first attempt.
**Why.** Retrying a non-idempotent write whose first attempt reached the server creates duplicates (two orders, two charges), and retrying a validation, not-found or permission error only repeats the same answer while the user waits.
**Exceptions.** A write becomes safe to retry once the server deduplicates it by a key the client generates once per logical operation and sends on every attempt.
### Branch on a ServiceError's kind flags, never on its message
_high · typescript_
**Rule.** Choose the response to a `ServiceError` from its boolean flags (or its `code`), most specific first, and fall through to one generic branch for everything else.
**Why.** A branch on message text breaks silently when someone rewords the message, and one generic branch for every error shows "Something went wrong" for a duplicate name the user could have fixed.
**Correct:**
```ts
const [error, thing] = await createThing(input);
if (error) {
// log it once here, with the error and the operation's ids
if (error.isAlreadyExists) return showError("A thing with this name exists");
if (error.isRetryable) return showError("Please try again in a moment");
return showError("Could not create the thing");
}
```
### Add a layer's own error codes in a ServiceError subclass, never a separate error type
_high · typescript_
**Rule.** Keep one `ServiceError` base whose `code`, `isRetryable`, `retryAfterMs`, `cause` and kind flags (`isNotFound`, `isAlreadyExists`, `isPermissionDenied`) every error type shares, with the shared codes in its `ServiceErrorCode` object. A layer that needs a failure the shared codes cannot name (an API client, a payment adapter) subclasses it in its own file, adding its codes as its own `as const` object passed as the type parameter, and its own factories, and never changes or drops a base member.
**Why.** A layer that defines its own error class has no `isRetryable` or kind flags, so the retry helper and every caller that branches on flags silently treat its failures as generic; adding its codes to the base instead fills the shared list with codes only one layer uses.
**Correct:**
```ts
// in the payment layer's own file
export const PaymentErrorCode = { CARD_DECLINED: "card-declined" } as const;
export type PaymentErrorCode = (typeof PaymentErrorCode)[keyof typeof PaymentErrorCode];
export class PaymentError extends ServiceError<PaymentErrorCode> {
static cardDeclined() {
return new PaymentError(PaymentErrorCode.CARD_DECLINED, "Your card was declined");
}
}
export async function charge(input: ChargeInput): Promise<[PaymentError | ServiceError, null] | [null, Charge]> { … }
```
### Return expected failures as [error, data] tuples, not exceptions
_high · typescript_
**Decision.** Every exported function whose work can fail for a reason the caller must handle (a request, a query, a file, parsing outside input) returns `Promise<[E, null] | [null, T]>`, written as that tuple union in the signature, where `E` is the project's `ServiceError` or a subclass of it. The function that catches maps the raw error with `categorizeServiceError` or returns its layer's own factory error, and nothing throws across the boundary; callers pass errors up unchanged, and the one that decides what the user sees checks `if (error)`, which narrows `data` to `T`, branches on the error's flags and logs once. HTTP APIs are called only through one `request` helper per API. Bugs still throw, and where a result reaches its boundary (a UI handler, an HTTP response, a framework action, a page's loader that throws to the error boundary) it takes that boundary's own shape.
### Pass an abort signal with a timeout to every external call
_high · typescript_
**Rule.** Give every `fetch` and every SDK call that accepts a `signal` an `AbortSignal.timeout(ms)` sized to what the caller can wait. Map the resulting `TimeoutError` to the retryable `timeout` ServiceError code; an `AbortError` comes from another signal the caller aborted, so it is a cancellation and is never retried.
**Why.** `fetch` has no default deadline, so one upstream that stops answering holds the request, its caller and the user who waits on it until the platform kills the function.
**Correct:**
```ts
const response = await fetch(`${API_URL}/rates`, { signal: AbortSignal.timeout(5_000) });
```
**Exceptions.** When the call must also stop on another signal (the user navigated away), combine them with `AbortSignal.any([request.signal, AbortSignal.timeout(5_000)])`.
### Retry a service call only when the ServiceError is flagged isRetryable
_high · typescript_
**Rule.** Wrap only reads and keyed writes in the retry helper, and make the helper return immediately when `error.isRetryable` is false. A create or charge is retried only with an idempotency key generated once, outside the retried function.
**Why.** A helper that retries on any error re-runs a not-found or validation failure three times, and one that retries a create without a key inserts the same record several times when the first response was lost.
**Correct:**
```ts
const idempotencyKey = crypto.randomUUID();
const [error, order] = await withRetry(() => createOrder(input, idempotencyKey));
// inside withRetry, after each attempt:
if (!error || !error.isRetryable || attempt === MAX_ATTEMPTS) return [error, data];
```
### Return an [error, data] tuple from every function whose work can fail
_high · typescript_
**Rule.** Type every exported function whose work can fail for a reason the caller must handle (a request, a query, a file, parsing outside input) as `Promise<[ServiceError, null] | [null, T]>`, writing the tuple union in the signature. Wrap every call that can throw in one `try`, returning `[null, data]` on success and the caught error mapped onto the project's error type on failure; a function that only calls tuple-returning functions passes their error on unchanged. Never let an exception cross the function's boundary.
**Why.** A function that throws lets every caller forget the `try/catch`, and TypeScript cannot say which functions throw, so a failed request surfaces as an unhandled error instead of a message the caller chose; the tuple puts the error in the caller's hands at every call site, and the `if (error)` check narrows `data` to `T`.
**Correct:**
```ts
export async function loadThing(input: ThingInput): Promise<[ServiceError, null] | [null, Thing]> {
try {
return [null, await callThatCanFail(input)];
} catch (error) {
return [categorizeServiceError(error, "Thing"), null];
}
}
const [error, thing] = await loadThing(input);
if (error) return handle(error);
use(thing); // Thing
```
**Exceptions.** A programming error (a broken invariant, an impossible branch) still throws. Where a result reaches its boundary, it takes that boundary's shape instead: a UI event handler shows a message, an HTTP handler answers with a status, a page's loader throws to the error boundary. A module built on a Result library (`neverthrow`) converts to the tuple at its exported functions only.
### Send every call to an HTTP API through one request helper that checks response.ok
_high · typescript_
**Rule.** Write one `request` helper per API and call every endpoint only through a typed function built on it. The helper turns a response whose `ok` is false into the project's error type, applies the timeout and parses the body. A generated client's calls go through the same kind of wrapper, which turns both a thrown error and a returned error result (openapi-fetch returns `{ data, error, response }`) into the tuple; never call them straight from a component or an action.
**Why.** `fetch` resolves on a 404 or a 500, so a call that only `await`s `response.json()` hands the error body to the caller as if it were data; a helper written once makes the status check, the timeout and the parsing impossible to forget on the next endpoint.
**Correct:**
```ts
async function request<T>(resource: string, path: string, init: RequestInit, parse: (body: unknown) => T): Promise<[ServiceError, null] | [null, T]> {
const timeout = AbortSignal.timeout(5_000);
try {
const response = await fetch(`${API_URL}${path}`, { ...init, signal: init.signal ? AbortSignal.any([init.signal, timeout]) : timeout });
if (!response.ok) return [categorizeServiceError(response, resource), null];
return [null, parse(await response.json())];
} catch (error) {
return [categorizeServiceError(error, resource), null];
}
}
export function getThing(id: string): Promise<[ServiceError, null] | [null, Thing]> {
return request("Thing", `/things/${id}`, { method: "GET" }, ThingSchema.parse);
}
```
### Type a value of unknown shape as unknown and narrow it, never as any
_high · typescript_
**Rule.** Type data whose shape is not known yet (parsed JSON, a caught error, a third-party payload) as `unknown` and narrow it with a type guard or a schema parse before using it. Never write `any`, neither as an annotation nor as `as any`.
**Why.** `any` turns off checking for the value and everything derived from it, so a missing field or a wrong type compiles and fails only at runtime; `unknown` makes the compiler reject every use until the code has checked the shape.
**Correct:**
```ts
function readTitle(payload: unknown): string | null {
if (typeof payload === "object" && payload !== null && "title" in payload && typeof payload.title === "string") {
return payload.title.trim();
}
return null;
}
```
## Read when the task touches it
| Impact | Rule | Applies to |
| --- | --- | --- |
| medium | [Return an error from a tuple-returning function without logging it](references/rules.md#return-an-error-from-a-tuple-returning-function-without-logging-it) — A function returning an [error, data] tuple never logs its error, caught or passed on; its caller logs. | typescript |
| medium | [Import from another folder through the ~/ path alias, not a deep relative path](references/rules.md#import-from-another-folder-through-the--path-alias-not-a-deep-relative-path) — ../../.. paths break when a file moves and hide where the import comes from; ~/ is rooted at the source root. | typescript |
| medium | [Model a closed set of strings as an as const object plus a same-named type](references/rules.md#model-a-closed-set-of-strings-as-an-as-const-object-plus-a-same-named-type) — Never a TypeScript enum or a hand-written literal union; one const object is both the value and the type. | typescript |
| medium | [Refer to a closed-set value through its const object, never as a raw string literal](references/rules.md#refer-to-a-closed-set-value-through-its-const-object-never-as-a-raw-string-literal) — A raw literal in an Extract silently becomes never when a value is renamed; OrderStatus.PAID fails to compile instead. | typescript |
| medium | [Write array types as Array<T>, never T[]](references/rules.md#write-array-types-as-arrayt-never-t) — T[] binds tighter than \|, so string \| number[] means a string or an array of numbers, not an array of either. | typescript |
| low | [Keep tutorials, how-to guides, reference and explanation on separate pages](references/rules.md#keep-tutorials-how-to-guides-reference-and-explanation-on-separate-pages) — The Diátaxis split: each page serves one reader need, so none mixes lessons, recipes, facts and background. | any |
| low | [Record every public change in CHANGELOG.md in the Keep a Changelog format](references/rules.md#record-every-public-change-in-changelogmd-in-the-keep-a-changelog-format) — Each pull request that changes public behaviour adds an entry under Unreleased, grouped by kind. | any |
| low | [Comment only a reason the code cannot show](references/rules.md#comment-only-a-reason-the-code-cannot-show) — Default to no comment; write one only for a hidden constraint, a subtle invariant or a workaround. | typescript |
| low | [Write every warranted comment as a JSDoc block, not a // line](references/rules.md#write-every-warranted-comment-as-a-jsdoc-block-not-a--line) — A /** */ comment on a declaration shows in editor hovers; a // comment above it shows nowhere else. | typescript |
| low | [Name the [error, data] tuple with one generic alias in the error module, if at all](references/rules.md#name-the-error-data-tuple-with-one-generic-alias-in-the-error-module-if-at-all) — Optional: one type Result<T, E> = [E, null] \| [null, T] beside ServiceError; never a per-file alias or a wrapper class. | typescript |
| low | [Declare every named function with the function keyword](references/rules.md#declare-every-named-function-with-the-function-keyword) — A const arrow is not hoisted and throws if called before its line has run; a declaration is hoisted. | typescript |
| low | [Write a callback argument as an inline arrow function](references/rules.md#write-a-callback-argument-as-an-inline-arrow-function) — Arrow functions belong only where a callback is passed; there they keep the outer this and stay short. | typescript |
| low | [Type function members of an object type as method signatures](references/rules.md#type-function-members-of-an-object-type-as-method-signatures) — Write onDelete(id: string): void, not onDelete: (id: string) => void, so the members match function declarations. | typescript |
Files in this skill
- SKILL.md
- references/rules.md
Attribution
Related skills
View all in development →Comments
Loading comments…
Newsletter
Get the weekly list of safe new skills, and the ones we pulled.