Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
.cursor/rules/typescript-strict-mode-development.mdc. Downloaded files need to be placed in that repository path.---
description: "Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs."
globs: "**/*"
alwaysApply: false
---
Apply these rules when writing TypeScript in this project.
## Compiler configuration
```json
{
"compilerOptions": {
"strict": true,
"noUncheckedIndexedAccess": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"exactOptionalPropertyTypes": true,
"noPropertyAccessFromIndexSignature": true
}
}
```
- `strict` is the default from TypeScript 6.0 but keep it explicit. The other options are not part of `strict`; keep the ones the project has enabled and fix errors rather than disabling them.
## Type definitions
```ts
// Object shapes: interface (or type, consistently)
interface User {
id: UserId;
email: string;
name: string;
role: 'admin' | 'user' | 'guest';
passwordHash: string;
createdAt: Date;
}
// Unions, intersections and derived types: type
type UserRole = User['role'];
type PublicUser = Omit<User, 'passwordHash'>;
type Nullable<T> = T | null;
interface ApiResponse<T> {
success: boolean;
data: T;
error?: string;
}
// Literal unions from a runtime list
const ROLES = ['admin', 'user', 'guest'] as const;
type Role = (typeof ROLES)[number]; // 'admin' | 'user' | 'guest'
```
- `Omit` does not report a key that does not exist on the source type (its key parameter is not constrained to `keyof T`); check omitted key names when the source type changes.
## Type guards
A guard must check what it claims. Check the type of each property it promises:
```ts
function isUserLike(value: unknown): value is Pick<User, 'id' | 'email'> {
return (
typeof value === 'object' &&
value !== null &&
'id' in value && typeof value.id === 'string' &&
'email' in value && typeof value.email === 'string'
);
}
```
For whole API payloads, prefer a schema validator (Zod, Valibot) over hand-written guards.
## Discriminated unions
```ts
type Result<T> =
| { success: true; data: T }
| { success: false; error: string };
function handleResult<T>(result: Result<T>): T {
if (result.success) return result.data; // data exists here
throw new Error(result.error); // error exists here
}
```
## Utility types
- Use the built-ins (`Partial`, `Required`, `Pick`, `Omit`, `Record`, `Extract`, `Exclude`, `NonNullable`, `ReturnType`, `Awaited`) instead of redefining them.
- With `noUncheckedIndexedAccess`, `Record<string, User>` lookups return `User | undefined`; use `Map` or narrow before use.
## Advanced patterns
```ts
// Branded IDs: a PostId cannot be passed where a UserId is expected
type UserId = string & { readonly __brand: 'UserId' };
type PostId = string & { readonly __brand: 'PostId' };
function toUserId(id: string): UserId {
// validate format here if IDs have one
return id as UserId;
}
// Template literal types
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';
type ApiEndpoint = `/api/${string}`;
type ApiRoute = `${HttpMethod} ${ApiEndpoint}`;
```
- Create branded values only in one constructor function per brand, so the `as` cast lives in one place.
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.
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.
Cursor
general
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
A codebase passes plain string IDs between user and post functions, its isUser guard only checks that keys exist, and it redefines NonNullable locally.
Using the TypeScript Strict Mode Development rule, review src/types.ts and src/guards.ts and propose changes.
Branded UserId/PostId types with one constructor each, guards that check property types (or a schema validator for payloads), the local NonNullable removed in favour of the built-in, PublicUser derived with Omit from a User that actually has passwordHash, and compiler options kept with errors fixed rather than suppressed.
Cursor applies project rules stored as .mdc files in .cursor/rules. Each rule's frontmatter (description, globs, alwaysApply) decides whether it is always included, attached to matching files, chosen by the agent from its description, or only used when you @-mention it. Cursor also reads AGENTS.md in the project root and subdirectories for plain-Markdown instructions.
.cursor/rules/typescript-strict-mode-development.mdcStarting point, not a tested configuration for your repository. Attached when files matching the globs are in context (alwaysApply: false with globs). Review the instructions, adapt the file paths and run your project's existing checks.
---
description: "TypeScript Strict Mode Development project conventions"
globs: "**/*"
alwaysApply: false
---
Apply these rules when writing TypeScript in this project.
## Compiler configuration
```json
{
"compilerOptions": {
"strict": true,
"noUncheckedIndexedAccess": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"exactOptionalPropertyTypes": true,
"noPropertyAccessFromIndexSignature": true
}
}
```
- `strict` is the default from TypeScript 6.0 but keep it explicit. The other options are not part of `strict`; keep the ones the project has enabled and fix errors rather than disabling them.
## Type definitions
```ts
// Object shapes: interface (or type, consistently)
interface User {
id: UserId;
email: string;
name: string;
role: 'admin' | 'user' | 'guest';
passwordHash: string;
createdAt: Date;
}
// Unions, intersections and derived types: type
type UserRole = User['role'];
type PublicUser = Omit<User, 'passwordHash'>;
type Nullable<T> = T | null;
interface ApiResponse<T> {
success: boolean;
data: T;
error?: string;
}
// Literal unions from a runtime list
const ROLES = ['admin', 'user', 'guest'] as const;
type Role = (typeof ROLES)[number]; // 'admin' | 'user' | 'guest'
```
- `Omit` does not report a key that does not exist on the source type (its key parameter is not constrained to `keyof T`); check omitted key names when the source type changes.
## Type guards
A guard must check what it claims. Check the type of each property it promises:
```ts
function isUserLike(value: unknown): value is Pick<User, 'id' | 'email'> {
return (
typeof value === 'object' &&
value !== null &&
'id' in value && typeof value.id === 'string' &&
'email' in value && typeof value.email === 'string'
);
}
```
For whole API payloads, prefer a schema validator (Zod, Valibot) over hand-written guards.
## Discriminated unions
```ts
type Result<T> =
| { success: true; data: T }
| { success: false; error: string };
function handleResult<T>(result: Result<T>): T {
if (result.success) return result.data; // data exists here
throw new Error(result.error); // error exists here
}
```
## Utility types
- Use the built-ins (`Partial`, `Required`, `Pick`, `Omit`, `Record`, `Extract`, `Exclude`, `NonNullable`, `ReturnType`, `Awaited`) instead of redefining them.
- With `noUncheckedIndexedAccess`, `Record<string, User>` lookups return `User | undefined`; use `Map` or narrow before use.
## Advanced patterns
```ts
// Branded IDs: a PostId cannot be passed where a UserId is expected
type UserId = string & { readonly __brand: 'UserId' };
type PostId = string & { readonly __brand: 'PostId' };
function toUserId(id: string): UserId {
// validate format here if IDs have one
return id as UserId;
}
// Template literal types
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';
type ApiEndpoint = `/api/${string}`;
type ApiRoute = `${HttpMethod} ${ApiEndpoint}`;
```
- Create branded values only in one constructor function per brand, so the `as` cast lives in one place.
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.
Cursor's docs recommend keeping individual rules under 500 lines and splitting large rules into composable ones. Cursor's documentation states that it supports AGENTS.md in the project root and in subdirectories. Use AGENTS.md for plain-Markdown instructions you also want other tools to read, and .mdc rules when you need Cursor's scoping options (globs, description-based selection, always-apply).
Documentation checked 2026-11-05: Cursor docs: Rules
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.
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.