TypeScript generics that stay readable: constraints, inference-friendly factories, mapped and conditional types, infer, and when not to add a type parameter.
.cursor/rules/typescript-generic-patterns.mdc. Downloaded files need to be placed in that repository path.---
description: "TypeScript generics that stay readable: constraints, inference-friendly factories, mapped and conditional types, infer, and when not to add a type parameter."
globs: "**/*"
alwaysApply: false
---
Apply these rules when writing generic TypeScript.
## When to add a type parameter
- Add a type parameter only when it links two or more positions (an input to an output, or two inputs). If it appears once, use the concrete type or `unknown` instead.
- Let TypeScript infer type arguments from values; callers should rarely write `fn<Type>(...)`.
## Constraints
- Constrain to what you use: `<T extends { id: string }>`, `<K extends keyof T>`.
```ts
export function indexBy<T, K extends keyof T>(items: readonly T[], key: K): Map<T[K], T> {
return new Map(items.map((item) => [item[key], item]));
}
```
## Factories
```ts
export function createStore<State>(initial: State) {
let state = initial;
return {
get: (): State => state,
set: (next: State | ((prev: State) => State)) => {
state = typeof next === 'function' ? (next as (prev: State) => State)(state) : next;
},
};
}
```
- Return inferred types from small factories; annotate the return type explicitly on exported APIs where it documents the contract.
## Mapped and conditional types
```ts
export type Nullable<T> = { [K in keyof T]: T[K] | null };
export type Getters<T> = { [K in keyof T & string as `get${Capitalize<K>}`]: () => T[K] };
export type ElementOf<T> = T extends readonly (infer U)[] ? U : never;
export type AsyncReturn<F extends (...args: any) => Promise<unknown>> = Awaited<ReturnType<F>>;
```
- Prefer built-in utility types (`Partial`, `Pick`, `Omit`, `Record`, `ReturnType`, `Awaited`, `NonNullable`) before writing your own; do not redefine names that shadow them.
- Conditional types distribute over unions; wrap in a tuple (`[T] extends [U]`) when you do not want that.
## Avoid over-generalization
- If a generic signature needs several conditional types to type-check, consider overloads or two simpler functions.
- Avoid `any` in constraints except in the standard `(...args: any) => unknown` function-shape pattern.
## Documentation
- Document each type parameter with `@typeParam` in TSDoc when its role is not obvious from the name; use descriptive names (`TItem`, `TKey`) when there is more than one.
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 strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
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.
Cursor
language
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
A utilities file has generic helpers with unused type parameters, callers passing explicit type arguments everywhere, and a custom NonNullable that shadows the built-in.
Apply the TypeScript Generic Patterns rule to src/lib/collections.ts and src/lib/types.ts.
Type parameters that appear only once are removed, helpers like indexBy constrain K to keyof T so inference works without explicit arguments, the shadowing NonNullable is removed in favour of the built-in, and each remaining type parameter has a @typeParam note where needed.
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-generic-patterns.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 Generic Patterns project conventions"
globs: "**/*"
alwaysApply: false
---
Apply these rules when writing generic TypeScript.
## When to add a type parameter
- Add a type parameter only when it links two or more positions (an input to an output, or two inputs). If it appears once, use the concrete type or `unknown` instead.
- Let TypeScript infer type arguments from values; callers should rarely write `fn<Type>(...)`.
## Constraints
- Constrain to what you use: `<T extends { id: string }>`, `<K extends keyof T>`.
```ts
export function indexBy<T, K extends keyof T>(items: readonly T[], key: K): Map<T[K], T> {
return new Map(items.map((item) => [item[key], item]));
}
```
## Factories
```ts
export function createStore<State>(initial: State) {
let state = initial;
return {
get: (): State => state,
set: (next: State | ((prev: State) => State)) => {
state = typeof next === 'function' ? (next as (prev: State) => State)(state) : next;
},
};
}
```
- Return inferred types from small factories; annotate the return type explicitly on exported APIs where it documents the contract.
## Mapped and conditional types
```ts
export type Nullable<T> = { [K in keyof T]: T[K] | null };
export type Getters<T> = { [K in keyof T & string as `get${Capitalize<K>}`]: () => T[K] };
export type ElementOf<T> = T extends readonly (infer U)[] ? U : never;
export type AsyncReturn<F extends (...args: any) => Promise<unknown>> = Awaited<ReturnType<F>>;
```
- Prefer built-in utility types (`Partial`, `Pick`, `Omit`, `Record`, `ReturnType`, `Awaited`, `NonNullable`) before writing your own; do not redefine names that shadow them.
- Conditional types distribute over unions; wrap in a tuple (`[T] extends [U]`) when you do not want that.
## Avoid over-generalization
- If a generic signature needs several conditional types to type-check, consider overloads or two simpler functions.
- Avoid `any` in constraints except in the standard `(...args: any) => unknown` function-shape pattern.
## Documentation
- Document each type parameter with `@typeParam` in TSDoc when its role is not obvious from the name; use descriptive names (`TItem`, `TKey`) when there is more than one.
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 strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
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.