TypeScript type guards: typeof, instanceof, in, discriminated unions, user-defined predicates, assertion functions, inferred predicates and exhaustive never checks.
.cursor/rules/typescript-type-guards.mdc. Downloaded files need to be placed in that repository path.---
description: "TypeScript type guards: typeof, instanceof, in, discriminated unions, user-defined predicates, assertion functions, inferred predicates and exhaustive never checks."
globs: "**/*"
alwaysApply: false
---
Apply these rules when narrowing types in TypeScript.
## Built-in narrowing
- `typeof` for primitives (`'string'`, `'number'`, `'bigint'`, `'boolean'`, `'symbol'`, `'undefined'`, `'function'`). Remember `typeof null === 'object'`.
- `instanceof` for class instances (including `Error` subclasses). It does not work for plain objects or for values from another realm (iframes, some test environments).
- `'key' in value` for checking that a property exists on an object union member.
- `Array.isArray` for arrays.
## Discriminated unions
- Give union members a literal `kind`/`type`/`status` field and switch on it. This is the most reliable narrowing and needs no custom guard.
## User-defined guards
```ts
interface Point { x: number; y: number }
export function isPoint(value: unknown): value is Point {
return (
typeof value === 'object' && value !== null &&
'x' in value && typeof value.x === 'number' &&
'y' in value && typeof value.y === 'number'
);
}
```
- A guard is a promise to the compiler: it must check every property it claims, or the code after it is unsound. For large payloads use a schema validator.
- Since TypeScript 5.5, simple arrow functions such as `items.filter((x) => x !== undefined)` infer a type predicate, so explicit `x is T` annotations are often unnecessary there.
## Assertion functions
```ts
export function assertIsDefined<T>(value: T, name: string): asserts value is NonNullable<T> {
if (value === undefined || value === null) {
throw new Error(`${name} is required`);
}
}
```
- Use assertion functions at boundaries (config loading, test setup) where failing fast is right. Assertion functions must be declared with an explicit type annotation when called through a variable.
## Progressive narrowing
- Narrow step by step with early returns (`if (!user) return;`) so later code works with the narrowed type; avoid nested conditions and `!`.
## Exhaustiveness
```ts
type Shape = { kind: 'circle'; r: number } | { kind: 'square'; size: number };
export function area(shape: Shape): number {
switch (shape.kind) {
case 'circle': return Math.PI * shape.r ** 2;
case 'square': return shape.size ** 2;
default: {
const unreachable: never = shape;
throw new Error(`Unhandled shape: ${JSON.stringify(unreachable)}`);
}
}
}
```
- Assigning to `never` turns a forgotten union member into a compile error.
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 geometry module adds a 'triangle' shape; area() silently returns undefined for it, and an isPoint guard only checks `'x' in value`.
Apply the TypeScript Type Guards rule to src/geometry.ts and src/validation.ts.
area() switches on shape.kind with a never default so the missing triangle case is a compile error, isPoint checks both property types, filter callbacks rely on inferred predicates, and config loading uses an assertIsDefined assertion function.
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-type-guards.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 Type Guards project conventions"
globs: "**/*"
alwaysApply: false
---
Apply these rules when narrowing types in TypeScript.
## Built-in narrowing
- `typeof` for primitives (`'string'`, `'number'`, `'bigint'`, `'boolean'`, `'symbol'`, `'undefined'`, `'function'`). Remember `typeof null === 'object'`.
- `instanceof` for class instances (including `Error` subclasses). It does not work for plain objects or for values from another realm (iframes, some test environments).
- `'key' in value` for checking that a property exists on an object union member.
- `Array.isArray` for arrays.
## Discriminated unions
- Give union members a literal `kind`/`type`/`status` field and switch on it. This is the most reliable narrowing and needs no custom guard.
## User-defined guards
```ts
interface Point { x: number; y: number }
export function isPoint(value: unknown): value is Point {
return (
typeof value === 'object' && value !== null &&
'x' in value && typeof value.x === 'number' &&
'y' in value && typeof value.y === 'number'
);
}
```
- A guard is a promise to the compiler: it must check every property it claims, or the code after it is unsound. For large payloads use a schema validator.
- Since TypeScript 5.5, simple arrow functions such as `items.filter((x) => x !== undefined)` infer a type predicate, so explicit `x is T` annotations are often unnecessary there.
## Assertion functions
```ts
export function assertIsDefined<T>(value: T, name: string): asserts value is NonNullable<T> {
if (value === undefined || value === null) {
throw new Error(`${name} is required`);
}
}
```
- Use assertion functions at boundaries (config loading, test setup) where failing fast is right. Assertion functions must be declared with an explicit type annotation when called through a variable.
## Progressive narrowing
- Narrow step by step with early returns (`if (!user) return;`) so later code works with the narrowed type; avoid nested conditions and `!`.
## Exhaustiveness
```ts
type Shape = { kind: 'circle'; r: number } | { kind: 'square'; size: number };
export function area(shape: Shape): number {
switch (shape.kind) {
case 'circle': return Math.PI * shape.r ** 2;
case 'square': return shape.size ** 2;
default: {
const unreachable: never = shape;
throw new Error(`Unhandled shape: ${JSON.stringify(unreachable)}`);
}
}
}
```
- Assigning to `never` turns a forgotten union member into a compile error.
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.