CLAUDE.md rules for strict TypeScript 5.9 with unknown at boundaries, satisfies over assertions, exhaustive unions, validated branded IDs and tested utility types.
.claude/rules/claude-typescript-expert.md. Downloaded files need to be placed in that repository path.---
paths:
- "**/*"
---
# TypeScript Conventions
Applies to: all TypeScript in this repository (application code, libraries, scripts and tests).
Version baseline: checked against TypeScript 5.9. Read `package.json` for the installed version and `tsconfig.json` for the compiler options. Don't loosen `strict`, and don't add `skipLibCheck` or `// @ts-ignore` to make errors disappear.
## Compiler settings
- Keep `strict: true`. When the project allows it, prefer adding `noUncheckedIndexedAccess`, `exactOptionalPropertyTypes` and `noImplicitOverride`, but propose the change first because it can produce many errors.
- Fix type errors at their source. If a suppression is truly needed, use `// @ts-expect-error <reason>`, which fails once the error is gone.
## Everyday rules
- Don't use `any`. Accept `unknown` at trust boundaries (JSON, `catch` variables, third-party data) and narrow it with type guards or a schema validator.
- Avoid `as` assertions. Use `satisfies` to check an object against a type without widening it.
- Let inference work for locals. Annotate exported function parameters and return types.
- Model variants as discriminated unions and check them exhaustively.
```ts
type Shape =
| { kind: 'circle'; radius: number }
| { kind: 'rectangle'; width: number; height: number }
| { kind: 'triangle'; base: number; height: number };
function assertNever(value: never): never {
throw new Error(`Unhandled variant: ${JSON.stringify(value)}`);
}
export function area(shape: Shape): number {
switch (shape.kind) {
case 'circle':
return Math.PI * shape.radius ** 2;
case 'rectangle':
return shape.width * shape.height;
case 'triangle':
return (shape.base * shape.height) / 2;
default:
return assertNever(shape); // adding a variant makes this a compile error
}
}
```
## Branded (nominal) types
Use brands for IDs and units that are easy to mix up, and create them only through a validating constructor.
```ts
declare const brand: unique symbol;
type Brand<T, B extends string> = T & { readonly [brand]: B };
export type UserId = Brand<string, 'UserId'>;
export type PostId = Brand<string, 'PostId'>;
export function toUserId(raw: string): UserId {
if (!raw.startsWith('user_')) throw new Error(`Not a user id: ${raw}`);
return raw as UserId;
}
declare function getUser(id: UserId): void;
declare const postId: PostId;
getUser(toUserId('user_123'));
// @ts-expect-error a PostId is not a UserId
getUser(postId);
```
## Utility types
- Prefer built-ins (`Partial`, `Required`, `Pick`, `Omit`, `Record`, `ReturnType`, `Awaited`, `NoInfer`) over custom helpers.
- When you write a helper, cover arrays and functions, and add a type-level test.
```ts
export type RequireFields<T, K extends keyof T> = T & Required<Pick<T, K>>;
export type DeepPartial<T> = T extends (...args: never[]) => unknown
? T
: T extends readonly (infer U)[]
? readonly DeepPartial<U>[]
: T extends object
? { [P in keyof T]?: DeepPartial<T[P]> }
: T;
export type Path<T> = T extends object
? { [K in keyof T & string]: T[K] extends object ? K | `${K}.${Path<T[K]>}` : K }[keyof T & string]
: never;
```
Keep recursive types shallow. Deep recursion slows the checker, so measure with `tsc --extendedDiagnostics` if builds get slower.
## Runtime boundaries
Types disappear at runtime. Validate external input (HTTP bodies, environment variables, `localStorage`, third-party API responses) with a schema library and derive the static type from the schema (for example `z.infer<typeof Schema>`).
## Verify before finishing
Run when available: `npx tsc --noEmit` (or `tsc -b` for project references), `npx eslint .` with typescript-eslint, and the tests. Type-level helpers need `@ts-expect-error` cases that fail when the helper breaks.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Stack-neutral CLAUDE.md conventions for Claude Code covering how to read before editing, keep diffs scoped, debug from a reproduction, test and report verification.
CLAUDE.md rules for React 19 with TypeScript covering typed components, derived state, compiler-aware memoization, useId-based accessibility and review checks.
Claude
general
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
Claude Code works in a strict TypeScript codebase with this file loaded as a project rule scoped to **/*.ts and **/*.tsx.
src/geometry.ts declares `const _exhaustive: never = shape` directly in a switch default, ids.ts mixes UserId and PostId strings, and types.ts has a DeepPartial that turns arrays into objects. Clean these up without loosening tsconfig (strict, noUncheckedIndexedAccess). TypeScript 5.9.
Illustrative; not a recorded model run. An assertNever helper used in the default branch so adding a variant fails to compile; branded UserId/PostId types created only through validating constructors, with a // @ts-expect-error line proving they cannot be swapped; DeepPartial that preserves functions and maps arrays element-wise; type-level tests with @ts-expect-error cases; no any, no ts-ignore, no tsconfig loosening; tsc and eslint results.
Claude Code loads persistent project instructions from CLAUDE.md files and from Markdown rules in .claude/rules/. Rules can be scoped to file paths with a paths frontmatter field, and CLAUDE.md can import other files with @path syntax. The rules in this directory are written as plain instruction prompts: in Claude Code, save them as CLAUDE.md or .claude/rules/ content; in Claude.ai or the Claude API, use the same text as project instructions or a system prompt instead.
.claude/rules/claude-typescript-expert.mdStarting point, not a tested configuration for your repository. Loaded when Claude Code works with files matching paths. Review the instructions, adapt the file paths and run your project's existing checks.
---
paths:
- "**/*"
---
# TypeScript Conventions
Applies to: all TypeScript in this repository (application code, libraries, scripts and tests).
Version baseline: checked against TypeScript 5.9. Read `package.json` for the installed version and `tsconfig.json` for the compiler options. Don't loosen `strict`, and don't add `skipLibCheck` or `// @ts-ignore` to make errors disappear.
## Compiler settings
- Keep `strict: true`. When the project allows it, prefer adding `noUncheckedIndexedAccess`, `exactOptionalPropertyTypes` and `noImplicitOverride`, but propose the change first because it can produce many errors.
- Fix type errors at their source. If a suppression is truly needed, use `// @ts-expect-error <reason>`, which fails once the error is gone.
## Everyday rules
- Don't use `any`. Accept `unknown` at trust boundaries (JSON, `catch` variables, third-party data) and narrow it with type guards or a schema validator.
- Avoid `as` assertions. Use `satisfies` to check an object against a type without widening it.
- Let inference work for locals. Annotate exported function parameters and return types.
- Model variants as discriminated unions and check them exhaustively.
```ts
type Shape =
| { kind: 'circle'; radius: number }
| { kind: 'rectangle'; width: number; height: number }
| { kind: 'triangle'; base: number; height: number };
function assertNever(value: never): never {
throw new Error(`Unhandled variant: ${JSON.stringify(value)}`);
}
export function area(shape: Shape): number {
switch (shape.kind) {
case 'circle':
return Math.PI * shape.radius ** 2;
case 'rectangle':
return shape.width * shape.height;
case 'triangle':
return (shape.base * shape.height) / 2;
default:
return assertNever(shape); // adding a variant makes this a compile error
}
}
```
## Branded (nominal) types
Use brands for IDs and units that are easy to mix up, and create them only through a validating constructor.
```ts
declare const brand: unique symbol;
type Brand<T, B extends string> = T & { readonly [brand]: B };
export type UserId = Brand<string, 'UserId'>;
export type PostId = Brand<string, 'PostId'>;
export function toUserId(raw: string): UserId {
if (!raw.startsWith('user_')) throw new Error(`Not a user id: ${raw}`);
return raw as UserId;
}
declare function getUser(id: UserId): void;
declare const postId: PostId;
getUser(toUserId('user_123'));
// @ts-expect-error a PostId is not a UserId
getUser(postId);
```
## Utility types
- Prefer built-ins (`Partial`, `Required`, `Pick`, `Omit`, `Record`, `ReturnType`, `Awaited`, `NoInfer`) over custom helpers.
- When you write a helper, cover arrays and functions, and add a type-level test.
```ts
export type RequireFields<T, K extends keyof T> = T & Required<Pick<T, K>>;
export type DeepPartial<T> = T extends (...args: never[]) => unknown
? T
: T extends readonly (infer U)[]
? readonly DeepPartial<U>[]
: T extends object
? { [P in keyof T]?: DeepPartial<T[P]> }
: T;
export type Path<T> = T extends object
? { [K in keyof T & string]: T[K] extends object ? K | `${K}.${Path<T[K]>}` : K }[keyof T & string]
: never;
```
Keep recursive types shallow. Deep recursion slows the checker, so measure with `tsc --extendedDiagnostics` if builds get slower.
## Runtime boundaries
Types disappear at runtime. Validate external input (HTTP bodies, environment variables, `localStorage`, third-party API responses) with a schema library and derive the static type from the schema (for example `z.infer<typeof Schema>`).
## Verify before finishing
Run when available: `npx tsc --noEmit` (or `tsc -b` for project references), `npx eslint .` with typescript-eslint, and the tests. Type-level helpers need `@ts-expect-error` cases that fail when the helper breaks.
Ask for a small change to one matching file. Check the tool's loaded context or instruction view, inspect the diff for the requested convention, and run the relevant build or test. A well-formatted file does not guarantee the model follows every instruction.
Imports with @path can nest up to four hops deep, according to the docs. Claude Code can read AGENTS.md as project instructions without extra configuration, but by default only when there is no CLAUDE.md in the working directory or above it. The docs list this behavior for version 2.1.277 and later and describe a setting (claude-md-and-agents-md) that loads both files. If you maintain AGENTS.md for other tools, you can also import it from CLAUDE.md with @AGENTS.md.
Documentation checked 2026-11-05: Claude Code docs: Manage Claude's memory
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Stack-neutral CLAUDE.md conventions for Claude Code covering how to read before editing, keep diffs scoped, debug from a reproduction, test and report verification.
CLAUDE.md rules for React 19 with TypeScript covering typed components, derived state, compiler-aware memoization, useId-based accessibility and review checks.