Automated summary
This skill provides advanced TypeScript typing patterns — generic constraints, conditional and mapped types, template literal types, branded IDs, discriminated unions and the satisfies operator — so that `any` and casts can be replaced by precise types.
Strengths
- Concrete before/after snippets show how each pattern removes `any`, `as unknown` and unsafe casts
- Covers branded/nominal types to keep domain identifiers such as UserId and OrderId distinct at compile time
- Demonstrates exhaustive discriminated-union modeling for async state and state machines
- Explains conditional types with `infer` and their distributive behaviour, plus constraints like `K extends keyof T`
Limitations
- Requires TypeScript ≥ 5.0 with strict mode enabled, otherwise the patterns catch nothing
- Deliberately excludes React prop typing and Zod schema/type sync, which are pointed to sibling skills
- Branded types only enforce at compile time — the casts at system boundaries add no runtime validation
Use it when your types are too loose, or when building a reusable library or SDK that needs precise generic signatures.
Skip it for React component props or runtime schema validation, which are handled by other skills.
Security analysis
SafeThe skill contains only TypeScript code examples and educational content. There are no instructions to execute commands, access networks, or perform any actions beyond writing code. No allowed tools are declared, so the skill cannot trigger any system operations. The content is purely advisory and poses no execution risk.
No concerns found
How this analysis is madeExamples
All my userId, orderId and productId are plain strings, so TypeScript lets me pass the wrong one everywhere. Show me how to add branded types so mixing them becomes a compile error.Model my data-fetching state (idle, loading, success, error) with a discriminated union and write a render function that fails to compile if I forget a case.I have a union of event types like USER_LOGIN, PAGE_VIEW and PURCHASE. Write a mapped type that derives a typed handler map from that union using Extract.name: typescript-patterns description: > Write precise TypeScript — generic constraints, conditional types, mapped types, template literal types, branded/nominal types, type narrowing, satisfies operator, and utility type composition. Use when asked about "TypeScript generics", "conditional type", "mapped type", "infer keyword", "branded type", "nominal typing", "template literal type", "satisfies", "utility types", "type narrowing", "discriminated union", "type predicate", "TypeScript strict mode", "keyof typeof", or "TypeScript advanced patterns". Do NOT use for: React-specific TypeScript — see frontend-patterns. Do NOT use for: API type generation — see api-design. origin: yamtam-original license: MIT © 2026 Vũ Văn Tâm version: 1.0.0 compatibility: "TypeScript ≥ 5.0. strict: true required for all patterns."
When to Use
- Use when: types are too broad (
any,as unknown,as SomeTypecasts) - Use when: building a reusable library or SDK that needs precise generics
- Use when: needing runtime-safe IDs (userId vs orderId confusion)
- Use when: modeling complex state machines with discriminated unions
- Do NOT use for: React component prop types — see frontend-patterns
- Do NOT use for: Zod schema ↔ type sync — that's in api-design
Branded / Nominal Types
// Prevents mixing IDs from different domains at compile time
type Brand<T, B extends string> = T & { readonly _brand: B };
type UserId = Brand<string, 'UserId'>;
type OrderId = Brand<string, 'OrderId'>;
function getUser(id: UserId): Promise<User> { ... }
// Create branded values at system boundaries
const userId = '123' as UserId;
const orderId = '456' as OrderId;
getUser(userId); // ✅
getUser(orderId); // ❌ TypeScript error — OrderId is not UserId
getUser('123'); // ❌ string is not UserId
Discriminated Unions
// Exhaustive state modeling — TypeScript checks all cases
type AsyncState<T> =
| { status: 'idle' }
| { status: 'loading' }
| { status: 'success'; data: T }
| { status: 'error'; error: Error };
function render<T>(state: AsyncState<T>) {
switch (state.status) {
case 'idle': return <Idle />;
case 'loading': return <Spinner />;
case 'success': return <Data data={state.data} />;
case 'error': return <ErrorMsg error={state.error} />;
// TypeScript error if a case is missing (with noImplicitReturns)
}
}
Generic Constraints
// Constrain T to objects with a known shape
function pluck<T, K extends keyof T>(items: T[], key: K): T[K][] {
return items.map(item => item[key]);
}
const names = pluck([{ name: 'Alice', age: 30 }], 'name'); // string[]
pluck([{ name: 'Alice' }], 'missing'); // ❌ TypeScript error
// Constrain to objects with an id field
function findById<T extends { id: string }>(items: T[], id: string): T | undefined {
return items.find(i => i.id === id);
}
Conditional Types + infer
// Extract return type of async function
type Awaited<T> = T extends Promise<infer R> ? R : T;
type Result = Awaited<Promise<string>>; // string
// Extract first argument of a function
type FirstArg<T extends (...args: any[]) => any> =
T extends (first: infer F, ...rest: any[]) => any ? F : never;
type F = FirstArg<(id: string, limit: number) => void>; // string
// Distributive conditional types
type Nullable<T> = T extends null | undefined ? never : T;
type Clean = Nullable<string | null | undefined | number>; // string | number
Mapped Types
// Make all fields optional and readonly
type DeepReadonly<T> = {
readonly [K in keyof T]: T[K] extends object ? DeepReadonly<T[K]> : T[K];
};
// Create event handler map from event union
type EventHandlers<T extends { type: string }> = {
[K in T['type']]: (event: Extract<T, { type: K }>) => void;
};
type AppEvent =
| { type: 'USER_LOGIN'; userId: string }
| { type: 'PAGE_VIEW'; path: string }
| { type: 'PURCHASE'; amount: number };
const handlers: EventHandlers<AppEvent> = {
USER_LOGIN: ({ userId }) => console.log(userId),
PAGE_VIEW: ({ path }) => analytics.track(path),
PURCHASE: ({ amount }) => metrics.record(amount),
};
Template Literal Types
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
type Endpoint = `/${string}`;
type Route = `${HttpMethod} ${Endpoint}`;
const routes: Route[] = ['GET /users', 'POST /orders'];
const invalid: Route = 'FETCH /data'; // ❌ TypeScript error
// CSS property builder
type CSSProperty = `${string}-${'color' | 'size' | 'weight'}`;
satisfies Operator (TS 4.9+)
// satisfies: validate type without widening — keeps literal inference
const config = {
port: 3000,
env: 'production',
db: { host: 'localhost', port: 5432 },
} satisfies Partial<AppConfig>;
config.port; // type: number (not widened to AppConfig['port'])
config.env; // type: 'production' (literal, not string)
// vs `as AppConfig` — that would lose literal types
// vs `: AppConfig` — that would accept missing fields
Type Guards
// User-defined type guard
function isApiError(error: unknown): error is ApiError {
return typeof error === 'object' && error !== null
&& 'code' in error && 'message' in error;
}
try {
await api.call();
} catch (err) {
if (isApiError(err)) {
console.log(err.code); // typed as ApiError
} else {
throw err;
}
}
// Assertion function (throws instead of returning false)
function assertDefined<T>(val: T | undefined, name: string): asserts val is T {
if (val === undefined) throw new Error(`${name} must be defined`);
}
Anti-Fake-Pass Rules
Before claiming TypeScript types are production-quality, you MUST show:
- [ ]
strict: trueenabled — no partial strict mode - [ ] No
anyin public APIs — useunknown+ type guards instead - [ ] No unchecked
as Tcasts — add runtime assertion or type guard - [ ] IDs use branded types — no mixing of
stringID domains - [ ] State machines use discriminated unions — no
booleanflag soup - [ ] All
switchstatements over discriminated unions are exhaustive
Reference: gates/anti-fake-pass-gate.md
From the file to a first result
The download contains exactly the content displayed on this page. This copy may differ from the latest version in the source repository.
View the source and supporting filesThis download contains SKILL.md only. Any scripts, references, templates and dependencies are not included. Get the required files from the source, preserving their directory structure, before continuing.
1. Download the file
Download SKILL.mdFrom the root of a test project, save the file as .skill-downloads/advanced-typescript-patterns-mt6repn5/SKILL.md, or use the command below. This folder is for inspecting the skill before installation.
Command for macOS/Linux or WSL: requires a POSIX shell and curl. On Windows without WSL, use the download button and create the folder manually.
mkdir -p '.skill-downloads/advanced-typescript-patterns-mt6repn5' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/advanced-typescript-patterns-mt6repn5/download' --output '.skill-downloads/advanced-typescript-patterns-mt6repn5/SKILL.md.part' && mv '.skill-downloads/advanced-typescript-patterns-mt6repn5/SKILL.md.part' '.skill-downloads/advanced-typescript-patterns-mt6repn5/SKILL.md'2. Check prerequisites
Read SKILL.md before using it. If it references scripts or external services, inspect them and prepare the required access in your test environment.
Environment declared by the author: TypeScript ≥ 5.0. strict: true required for all patterns.
No recognized prerequisites section in this file. This does not mean it is self-contained: libraries, tools and access requirements may be mentioned elsewhere in the content or source repository.
The platforms on this page are catalog indications. The paths below follow tool documentation; they do not prove this skill has been run in those tools. No minimum tool version is confirmed for this listing.
3. Load the skill
After inspection, copy the complete folder into your project using one of the commands below, then open a new tool session. The command stops if a folder with the same name already exists: compare the files before replacing it.
Claude Code
test -f '.skill-downloads/advanced-typescript-patterns-mt6repn5/SKILL.md' && test -s '.skill-downloads/advanced-typescript-patterns-mt6repn5/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/typescript-patterns' && cp -R '.skill-downloads/advanced-typescript-patterns-mt6repn5' '.claude/skills/typescript-patterns'Cursor
test -f '.skill-downloads/advanced-typescript-patterns-mt6repn5/SKILL.md' && test -s '.skill-downloads/advanced-typescript-patterns-mt6repn5/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/typescript-patterns' && cp -R '.skill-downloads/advanced-typescript-patterns-mt6repn5' '.cursor/skills/typescript-patterns'Codex
test -f '.skill-downloads/advanced-typescript-patterns-mt6repn5/SKILL.md' && test -s '.skill-downloads/advanced-typescript-patterns-mt6repn5/SKILL.md' && mkdir -p '.agents/skills' && test ! -e '.agents/skills/typescript-patterns' && cp -R '.skill-downloads/advanced-typescript-patterns-mt6repn5' '.agents/skills/typescript-patterns'OpenSkills
OpenSkills must already be installed. The local install/read procedure is checked with OpenSkills 1.5.0, which requires Node.js ≥ 20.6.0. Catalog slugs are not resolved automatically.
Official OpenSkills installationopenskills install './.skill-downloads/advanced-typescript-patterns-mt6repn5'openskills read 'advanced-typescript-patterns-mt6repn5'Reading should display the installed file content and its base directory. It does not run the skill or install its dependencies.
For an agent that reads AGENTS.md, then sync the index. This command changes AGENTS.md: review the diff before using it.
openskills syncManual method or another tool: attach SKILL.md to a conversation, or open it in an agent that can read files. Include any required supporting resources. No universal folder is recognized by every tool.
4. Try a first task
Use a short, synthetic input: an API endpoint, a small document or an interface brief. In a new conversation, attach the file or give the agent its path, then adapt this request:
Read .skill-downloads/advanced-typescript-patterns-mt6repn5/SKILL.md and apply its instructions to this example: [describe a test input]. Identify any missing files, dependencies or access. Produce the result requested by the skill without inventing data or running unreviewed scripts.Expected result: output matching the skill instructions, or a precise list of missing prerequisites. A read confirmation alone does not validate a first use. If an external resource is unavailable, that path remains untested.
React Hook Form Best Practices
Development
Master React Hook Form: avoid anti-patterns, manage subscriptions, and handle reset, dirty state, and controlled inputs correctly.
Emotion to Mantine Migration
Development
Migrate Emotion styled-components to Mantine components with style props and CSS modules. Use when converting .styled.tsx files or removing @emotion imports.
Scope Creep Detector
Development
Analyzes git diffs against a stated intent to detect scope creep, unrelated files, broad PRs, and oversized changes, then suggests keep, split, or justify actions.