/dd:ts:corefrom dd:ts
TypeScript conventions covering code layout, DRY, control flow, functions, types, enums, Zod at boundaries, errors, async, module state, logging, classes, files, imports, comments, and naming. Load first when writing, changing, or reviewing TypeScript.
Ships in dd:ts. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
The conventions that govern essentially every TypeScript edit. Topic skills stack on top:
dd:ts:testing, dd:ts:tooling, dd:ts:library (published packages only).
bun fmt owns quotes, semicolons, wrapping and import order: no semicolons, single quotes,
100 columns (dd:ts:tooling). Write that way from the start. bun fmt does not place blank
lines, merge copies, or split a long function. Those three are the rules a review flags most, and only you
can follow them.
A function body is a run of paragraphs. A blank line separates two steps, never two statements. Both failures are common. A wall is twenty lines with no blank line. The opposite failure puts a blank line after every statement, so a three-line method has two blank lines.
One step = one paragraph. Lines that do one step — bind the inputs, start a process, build one value — stay together. A blank line goes between steps.
A short body has no blank lines. The whole body has up to ~4 statements, at most one of
them a one-line if, and no braced block. Most methods and helpers are short bodies. The last
lines of a long body are not a short body.
A braced block is its own paragraph. A blank line goes before and after an if { },
switch, try, for and while. Exceptions: the first and the last statement of a body.
ifs that test the same value one case at a time are one paragraph, braced ones too —
typeof value === 'bigint', then 'number'. They are the cases of a switch.
A one-line if is a statement, not a block. It gets no blank line of its own. A guard
(if (…) return or throw) joins one of these:
const x = …, then if (!x.ok) return …,
then the line that uses x: one step;return, when only that return follows the guard.A guard that joins none of them is a paragraph of its own. So a guard on a value bound earlier keeps the blank line after it, even when the next line uses that value.
One-line declarations of one group stay together — consts, class fields. A blank line
goes between groups.
A multi-line declaration is its own paragraph — a function, a class, a type, an enum,
an object on several lines. A blank line goes before and after it.
A declaration with a comment above it starts a new paragraph.
Blank line between class methods, always. One after the imports, one between import groups.
// One blank line per const — the file reads as a list of unrelated facts
const ANVIL_CONTAINER = 'adi-e2e-anvil'
const SERVER_CONTAINER = 'adi-e2e-server'
const ANVIL_PORT = 8545
const SERVER_PORT = 3050
// Groups — names, then ports
const ANVIL_CONTAINER = 'adi-e2e-anvil'
const SERVER_CONTAINER = 'adi-e2e-server'
const ANVIL_PORT = 8545
const SERVER_PORT = 3050
// Wall — five steps, no breaks
export const runCommand = async (command: string, args: string[]): Promise<string> => {
const start = performance.now()
log.command([command, ...args].map(quote).join(' '))
const proc = spawn(command, args)
const stdout = await collect(proc)
const code = await proc.exited
if (stop.signal.aborted) throw new Interrupted()
const took = duration(secondsSince(start))
if (code) {
log.fail(`✗ exit ${code} after ${took}`)
throw new Error(`${command} exited with ${code}`)
}
log.ok(`✓ ${took}`)
return stdout
}
// Paragraphs — announce, run, check, report
export const runCommand = async (command: string, args: string[]): Promise<string> => {
const start = performance.now()
log.command([command, ...args].map(quote).join(' '))
const proc = spawn(command, args)
const stdout = await collect(proc)
const code = await proc.exited
if (stop.signal.aborted) throw new Interrupted()
const took = duration(secondsSince(start))
if (code) {
log.fail(`✗ exit ${code} after ${took}`)
throw new Error(`${command} exited with ${code}`)
}
log.ok(`✓ ${took}`)
return stdout
}
// A blank line after every statement — a short body cut into three paragraphs
const parseCount = (raw: string): number | ParseError => {
if (!raw) return 0
const count = Number(raw)
return Number.isInteger(count) ? count : new ParseError(raw)
}
// Short body — three statements, one check: no blank lines
const parseCount = (raw: string): number | ParseError => {
if (!raw) return 0
const count = Number(raw)
return Number.isInteger(count) ? count : new ParseError(raw)
}
// Short body — a guard and the last return
const div = (a: bigint, b: bigint): bigint => {
if (!b) throw new RangeError('division by zero')
return a / b
}
// Two checks, so not a short body. path is bound earlier, so its guard keeps the blank line.
// text: bind, check, use.
const loadConfig = async (path: string): Promise<Config | ConfigError> => {
if (!path) return DEFAULT_CONFIG
const text = await readText(path)
if (text instanceof ReadError) return new ConfigError(path, { cause: text })
return parseConfig(text)
}
// Consecutive guards, then the loop as its own paragraph
const sqrtBigInt = (value: bigint): bigint => {
if (value < 0n) throw new RangeError(`${value} is negative`)
if (value < 2n) return value
let root = value
let next = (root + 1n) / 2n
while (next < root) {
root = next
next = (root + value / root) / 2n
}
return root
}
// Cases of one value are one paragraph, the braced case too
const toBigInt = (value: bigint | number | string): bigint => {
if (typeof value === 'bigint') return value
if (typeof value === 'number') {
assert(Number.isSafeInteger(value), `${value} is not a safe integer`)
return BigInt(value)
}
const text = value.trim()
assert(INTEGER.test(text), `"${value}" is not an integer`)
return BigInt(text)
}
When the arguments do not fit on one line, put one logical unit per line. A flag and its
value are one unit. bun fmt puts each string of a wrapped array on its own line, so it splits a
flag from its value — keep them as [flag, value] pairs and .flat() them at the call.
// Wall — which value belongs to which flag?
await runCommand('docker', [
'run', '-d', '--name', SERVER_CONTAINER, '--user', '0:0',
'--add-host', 'host.docker.internal:host-gateway', '-p', '3050:3050',
'--env-file', 'server/server.env', image,
])
// One pair per line, a comment sits next to its flag
await dockerRun(
[
['--name', SERVER_CONTAINER],
['--user', '0:0'], // the image runs as app, a new volume belongs to root
['--add-host', 'host.docker.internal:host-gateway'],
['-p', '3050:3050'],
['--env-file', 'server/server.env'],
],
image,
)
The usual advice — "three similar lines beat a premature abstraction" — does not apply here. In this codebase that default produced copy-paste. The second copy is the signal, not the third.
helpers/, in the module you are in, and in the module
that owns the concern. Use what exists; add an option to it if it lacks one.| Copy | Fix |
|---|---|
the same expression twice — Object.keys(scenarios).join(', ') | a const |
the same call prefix — runQuiet('docker', …) four times | a wrapper — docker(...args) |
| the same cleanup in two branches | one finally |
the same type check in two modules — typeof v === 'number' | one helper in helpers/, or a zod schema |
a second way to do what a module already does — a raw Bun.spawn next to runCommand | the module, extended |
two error values for one failure — new Error('interrupted') and new Interrupted() | one error class |
| the same literal in two files | one constant |
else. Invert the condition and return early. A one-line guard has no
braces: if (!id) return null. A ternary that hides an else inside a return is the same
thing — sink the special case into an early return.switch for a closed set — a return per case, a default that throws.for. Use map, filter, reduce, flatMap, and forEach for side effects.
for…of only for a sequential await or an early break. while only for an algorithm.?? for null/undefined. || only when '' and 0 must fall
through too.if (code), not if (code !== 0);
if (!bin), not if (bin === undefined || bin === ''). Compare explicitly only when 0 or
'' is a valid value.Arrow consts with an explicit return type: export const parseX = (raw: string): X => ….
function only for an assertion signature (asserts x).
An expression body fits on the signature line, or it becomes a block. When the arrow and
its expression do not fit in 100 columns, bun fmt moves the expression to the next line.
Write { return … } instead — and do not forget the return.
// Hanging body
export const adi = (run: Run, args: string[], opts: AdiOpts = {}): Promise<string> =>
runCommand(run.adiBin, args, { ...opts, display: 'adi', signal: run.signal })
// Block
export const adi = (run: Run, args: string[], opts: AdiOpts = {}): Promise<string> => {
return runCommand(run.adiBin, args, { ...opts, display: 'adi', signal: run.signal })
}
Short bodies — ~15 lines. Longer: extract a named step. The name replaces a comment.
At most 3 parameters. More: one options object, opts.
No positional booleans. parse(input, true) → an options object or an enum argument.
A query has no side effects. parseX, isX, toX return a value and write nothing.
Private helpers go below the exports that use them.
type, never interface. One form for every shape, and nobody can reopen a type from
another file by declaration merging.unknown, never any. No ! non-null assertion — use ?., ??, or assert().as casts except as const and a brand constructor. Narrow with a type predicate
(isX(v): v is X) or assert().Omit, Pick, Partial, Exclude, ReturnType, z.infer.type ChainId = Brand<bigint, 'ChainId'>, minted in
one constructor or by zod .brand(). An as ChainId anywhere else means the brand does
nothing.readonly on fields that never change. satisfies checks a literal without widening it.enum in PascalCase, members in PascalCase, string values:
export enum CheckState {
Done = 'done',
Waiting = 'waiting',
Failed = 'failed',
}
export type Check =
| { state: CheckState.Done; value: string }
| { state: CheckState.Waiting }
| { state: CheckState.Failed; reason: string }
as const object, not a bare string union for a closed set of values the code
defines — states, modes, units, and the options a caller passes to a public API. A string enum
rejects 'done' where a CheckState is expected (TS2322); as const and a union accept it.state === CheckState.Done, unit = TimeUnit.Millisecond.enum, not const enum — isolatedModules cannot inline it across files.enum needs erasableSyntaxOnly off (dd:ts:tooling).method: RequestInit['method']. Use its type; do not wrap it in an
enum.External data — command output, HTTP bodies, env vars, files — is unknown until a zod schema
parses it. Parse once at the edge; inside, trust the type.
const ServerParamsSchema = z.object({
genesis: z.string(),
genesis_chain_id: z.number().int(),
genesis_bridgehub_address: z.string(),
})
export type ServerParams = z.infer<typeof ServerParamsSchema>
export const parseServerParams = (json: string): ServerParams => {
return ServerParamsSchema.parse(JSON.parse(json))
}
z.infer. Never hand-write a type next to a schema.isNumber/isString chains on external data — the schema is the check.assert(), not zod.Promise<string | ReadError>. The caller narrows with instanceof, and the
compiler does not let it use the value before that.T | E, not a Result<T, E> wrapper. instanceof is the type guard. Use a wrapper only
when T itself can be an Error.'?', -1, '' or null that mean "it failed" look like a real
value, and the signature hides the failure. A display such as '?' belongs to the output
edge only.public name = 'X' as a field; the
caller narrows with instanceof.throw new Error('deploy failed', { cause: e }).catch (e) is unknown. Narrow with instanceof; format through one errorMessage(e)
helper.assert(cond, msg) over if (!cond) throw — one line, and it narrows. One shared
assert in helpers/.finally, not in each branch.catch {}. A deliberate ignore says why.instanceof and rethrow the
rest. A catch-all also hides your own bugs: a wrong ABI or a TypeError looks the same as a
failed request.// Magic value — the signature says string, and a failure is a string too
const read = async (value: () => Promise<bigint>): Promise<string> => {
try {
return String(await value())
} catch {
return '?'
}
}
// The error is in the type — a narrow catch, and the reason stays in the error
const read = async (value: () => Promise<bigint>): Promise<string | ReadError> => {
try {
return String(await value())
} catch (e) {
if (!(e instanceof BaseError)) throw e
return new ReadError(e.shortMessage, { cause: e })
}
}
// The output edge is the only place that knows about '?'
const show = (value: string | ReadError): string => {
return value instanceof ReadError ? '?' : value
}
export class Interrupted extends Error {
public name = 'Interrupted'
}
export function assert(condition: unknown, message: string): asserts condition {
if (!condition) throw new Error(message)
}
Promise.all; Promise.allSettled when partial success
counts.for…of + await only when a step needs the previous one or the order is the
point.void p.catch(handle)..forEach(async …) awaits nothing — use Promise.all(xs.map(…)) or for…of.await, not .then() chains. An inline .catch() stays for a fallback.AbortSignal. A timeout aborts on a timer; clearTimeout goes in finally.static async create() factory, a method.let at module scope. Several top-level lets that several functions
change are hidden global state.export const log = new Logger()), or one private config object that only one exported
setter changes.dayjs.extend(utc)) is
the exception.log.info,
log.title, log.error. No console.log, no process.stdout.write.FAILED: prefixes or padding at call sites.dd:ts:library).#field for private state. The private keyword only in a published library
(dd:ts:library).public on public members.getX() for derived or read-only values. Boolean getters: isX, hasX.bn/ → bn.ts, parsers.ts, format.ts,
round.ts).types/, enums/, const/, helpers/ (pure functions),
errors.ts. Domain code goes by feature, not by kind.@/ alias across directories, ./ inside one directory. Never ../.import type for type-only imports.node:), packages, @/, relative — with a blank line
between them. bun fmt with sortImports keeps this order.index.ts, and it holds only re-exports:
export * from './check-state'.@/enums), never a file behind it (@/enums/check-state). Moving or splitting a file then
changes one barrel, not every import../file, never through the own barrel. That
makes a cycle, and a cycle can give undefined at load time.// File paths — every import knows the layout of enums/ and lib/
import { CheckState } from '@/enums/check-state'
import { log } from '@/lib/logger'
// Modules
import { CheckState } from '@/enums'
import { log } from '@/lib'
Default to less. The failure to avoid is the comment poem: a prose block that explains the design to nobody.
// — 1 line or none. A TSDoc /** … */ — 1 line. An inline
// — 1–3 lines.Returns…, Starts… — and says what the
name and the types do not.@param / @returns that restate the signature. @throws only when the failure is
not obvious.// is for a why the code cannot show: a workaround, an ordering rule, a spec link. A
// that says what a block does means: extract a named function.// Too much — restates the signature, narrates the body
/**
* Runs the command, streams its stdout and stderr to the log, waits for the exit,
* and prints a check mark with the duration.
* @param command The command
* @param args The arguments
* @returns The stdout
*/
// Enough
/** Runs a logged command and fails on a non-zero exit. */
| Kind | Convention | Example |
|---|---|---|
| files, dirs | kebab-case | server-params.ts |
| types, classes, enums, enum members | PascalCase | CheckState.Done |
| constants | SCREAMING_SNAKE_CASE | FOUNDRY_IMAGE |
| functions, variables | camelCase | parseServerParams |
| type parameters | T, U, K, V | Brand<T, B> |
rpcUrl, HttpClient, parseJson — not RPCURL.isX/hasX — a boolean or a predicate; parseX — raw to
typed, throws; assertX — narrows or throws; buildX — builds from parts; toX — converts.get prefix on a plain accessor — use a getter.cfg, opts, e, acc.What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
Other plugins' skills for the same job
5 skills in this plugin
/libraryExtra TypeScript rules for a published package — the public API surface, package-prefixed names, private over/reviewComprehensive TypeScript code review — runs format, typecheck, lint and tests, loads the TypeScript convention skills, reviews the changes, and writes a structured report. Use when reviewing finished TypeScript changes, closing a slice that touched TypeScript, preparing a PR for merge, or auditing TypeScript code quality — not while writing the code./testingTypeScript testing with bun test — file layout, describe/test naming, arrange-act-assert, fixtures and mocks, asserting errors. Use whenever writing or reviewing TypeScript tests, setting up a test runner, organizing test files or fixtures, mocking dependencies, asserting on thrown errors, or when the user asks about test structure, coverage, or testing patterns in a TypeScript project./toolingTypeScript project tooling on Bun — bun as package manager, runtime and test runner, bun fmt for formatting and import order, bun lint for lint rules, bun check for types, bunfig.toml, tsconfig strictness flags, workspaces, and git hooks. Use whenever setting up or changing a TypeScript project's config, editing bunfig.toml or tsconfig.json, choosing format or lint settings, adding dependencies or scripts, configuring a monorepo workspace, setting up CI checks, or when the user asks about strict flags, lint rules, formatting, or which tools to use.npx claudepluginhub napalmpapalam/skills --plugin ts