typescript-advanced-patterns
БесплатноБез исполняемых скриптовНе проверенAdvanced TypeScript type system patterns for production codebases. [What: branded types for nominal typing, discriminated unions, template literal types…
от curiositech★ 283 звезды на GitHubОб этом скилле
TypeScript Advanced Patterns
Advanced type system patterns that eliminate runtime bugs by encoding constraints at compile time.
When to Use
Activate on: "branded types", "nominal typing", "discriminated union", "template literal types", "conditional types", "infer keyword", "satisfies operator", "const assertion", "Zod inference", "exhaustive switch", "type-safe event emitter", "mapped types", "utility types", "generic constraints", "type narrowing", "as const"
NOT for: Basic TypeScript syntax | React component prop types | General JavaScript patterns
Decision Tree: Which Advanced Pattern for Your Problem?
flowchart TD
P[What is your problem?] --> P1[I'm mixing up\nvalues of the same type\ne.g. UserId vs OrderId]
P[What is your problem?] --> P2[I have a value that\ncan be one of N shapes]
P[What is your problem?] --> P3[I need type-safe\nevent emitting]
P[What is your problem?] --> P4[I'm parsing external\ndata and want types]
P[What is your problem?] --> P5[I want types that\ndepend on other types]
P[What is your problem?] --> P6[My switch/if is\nnot exhaustive]
P1 --> S1[Branded Types\nfor nominal typing]
P2 --> S2[Discriminated Unions\nwith type narrowing]
P3 --> S3[Type-Safe Event Emitter\nwith mapped types]
P4 --> S4[Zod schema + z.infer\nfor runtime + compile time]
P5 --> S5[Conditional Types\nwith infer keyword]
P6 --> S6[Exhaustive checking\nwith never type]
Core Patterns
1. Branded Types (Nominal Typing)
TypeScript's structural type system means UserId and string are assignable to each other. Branded types add a phantom brand that makes them incompatible.
// Without branding: these compile without error
function chargeUser(userId: string, amount: number) { /* ... */ }
const orderId = getOrderId();
chargeUser(orderId, 100); // Wrong! orderId passed as userId — TypeScript allows it
// With branding: compile-time protection
type Brand<T, B extends string> = T & { readonly __brand: B };
type UserId = Brand<string, 'UserId'>;
type OrderId = Brand<string, 'OrderId'>;
type EmailAddress = Brand<string, 'EmailAddress'>;
type Cents = Brand<number, 'Cents'>; // Never pass raw numbers as money
// Constructor functions (only way to create branded values)
const UserId = (id: string): UserId => id as UserId;
const OrderId = (id: string): OrderId => id as OrderId;
const Cents = (n: number): Cents => {
if (!Number.isInteger(n) || n < 0) throw new Error(`Invalid cents: ${n}`);
return n as Cents;
};
// Usage: type error if you mix them up
function chargeUser(userId: UserId, amount: Cents) { /* ... */ }
const uid = UserId('user_123');
const oid = OrderId('order_456');
chargeUser(uid, Cents(1000)); // OK
chargeUser(oid, Cents(1000)); // Error: Argument of type 'OrderId' is not assignable to 'UserId'
chargeUser(uid, 1000); // Error: Argument of type 'number' is not assignable to 'Cents'
See references/branded-types.md for Zod integration and database model patterns.
2. Discriminated Unions with Type Narrowing
The kind (or type, tag) field is the discriminant. TypeScript narrows the union when you check it.
type ApiResult<T> =
| { status: 'success'; data: T }
| { status: 'error'; code: number; message: string }
| { status: 'loading' };
function handleResult<T>(result: ApiResult<T>): T | null {
switch (result.status) {
case 'success': return result.data; // TypeScript knows data exists here
case 'error': console.error(result.code, result.message); return null;
case 'loading': return null;
}
}
With exhaustive checking — if a new variant is added and the switch is not updated, it's a compile error:
function assertNever(x: never): never {
throw new Error(`Unexpected value: ${JSON.stringify(x)}`);
}
function handleResult<T>(result: ApiResult<T>): T | null {
switch (result.status) {
case 'success': return result.data;
case 'error': return null;
// If 'loading' is not handled, TypeScript errors:
// Argument of type '{ status: "loading" }' is not assignable to 'never'
default: return assertNever(result);
}
}
3. Template Literal Types
Combine string literals at type level to create precise types for string-based APIs:
// Route path types — prevents typos in route definitions
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
type ApiVersion = 'v1' | 'v2';
type Resource = 'users' | 'orders' | 'products';
type ApiEndpoint = `/${ApiVersion}/${Resource}`;
// Type: "/v1/users" | "/v1/orders" | "/v1/products" | "/v2/users" | ...
// CSS-in-JS property types
type CSSProperty = 'margin' | 'padding' | 'border';
type Side = 'top' | 'right' | 'bottom' | 'left';
type CSSPropertyWithSide = `${CSSProperty}-${Side}`;
// Type: "margin-top" | "margin-right" | ... | "border-left"
// Event name types
type DOMEventMap = {
click: MouseEvent;
keydown: Keyboar
Установить typescript-advanced-patterns в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
ReadWriteEditBash(npm:*,npx:*,tsc:*)Вложенные файлы
FAQ
Что делает скилл typescript-advanced-patterns?
Advanced TypeScript type system patterns for production codebases. [What: branded types for nominal typing, discriminated unions, template literal types, conditional types, the infer keyword, satisfies operator, const assertions, Zod schema inference, type-safe event emitters, exhaustive switch checking] [When: designing domain models, building type-safe APIs, creating reusable generic utilities, eliminating runtime bugs with compile-time guarantees, refactoring any-typed codebases] [Keywords: branded types, discriminated union, template literal types, conditional types, infer, satisfies, const assertion, Zod inference, exhaustive, mapped types, utility types, nominal typing, type narrowing, generic constraints] NOT for basic TypeScript syntax or React component typing (use a React-specific skill).
Как установить скилл typescript-advanced-patterns?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл typescript-advanced-patterns запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
theme-factory
Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
от Anthropicaccess
Manage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropicconfigure
Set up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
от Anthropicaccess
Manage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropic