typescript-advanced-patterns · nickcrew — скилл для Claude Code
Скилл typescript-advanced-patterns для Claude Code проектирует сложные типы TypeScript — от брендированных идентификаторов до типобезопасных API. Выражает правила предметной области на уровне типов.
MIT 174 установок ★ 71 обновлён 2026-06-29
npx skills add NickCrew/Claude-Cortex --skill typescript-advanced-patterns -a claude-codeЧто делает typescript-advanced-patterns
Скилл подбирает продвинутые приёмы системы типов под задачу: условные и отображаемые типы, типы-шаблоны строк, type guards, дискриминируемые объединения, обобщения и паттерн Builder. Это помогает описывать состояния и ограничения API так, чтобы ошибки обнаруживались при проверке типов.
Работа устроена по шагам: определить требование, открыть подходящий материал из references, применить паттерн и проверить типы и поведение во время выполнения. В папке есть отдельные справки по темам, включая тестирование типов и частые ошибки. Скилл советует включить strict в tsconfig.json; слишком сложные вложенные типы замедляют компиляцию, поэтому их стоит держать неглубокими.
Какие задачи решает
- описать типобезопасный API с явными контрактами
- смоделировать состояния приложения дискриминируемым объединением
- разделить несовместимые строковые идентификаторы брендированными типами
- создать обобщённый Builder с ограничениями по шагам
- проверить типы и найти небезопасные утверждения
as
Примеры запросов агенту
- Спроектируй типобезопасный API для этих функций и выбери подходящие типы TypeScript.
- Смоделируй состояния загрузки, успеха и ошибки дискриминируемым объединением.
- Проверь эти типы на избыточную вложенность и предложи способ их упростить.
Как установить typescript-advanced-patterns
1Через Skills CLI (Vercel)
npx skills add NickCrew/Claude-Cortex --skill typescript-advanced-patterns -a claude-code2Вручную: положить файлы
~/.claude/skills/typescript-advanced-patterns/SKILL.mdПапка скилла целиком; для одного проекта — .claude/skills/typescript-advanced-patterns/
1Через Skills CLI (Vercel)
npx skills add NickCrew/Claude-Cortex --skill typescript-advanced-patterns -a codex2Вручную: положить файлы
.agents/skills/typescript-advanced-patterns/SKILL.mdДля всех проектов — ~/.agents/skills/
1Через Skills CLI (Vercel)
npx skills add NickCrew/Claude-Cortex --skill typescript-advanced-patterns -a cursor2Вручную: положить файлы
.cursor/skills/typescript-advanced-patterns/SKILL.mdCursor читает и .agents/skills/, и .claude/skills/
1GitHub CLI
gh skill install NickCrew/Claude-Cortex skills/typescript-advanced-patterns2Вручную: положить файлы
.github/skills/typescript-advanced-patterns/SKILL.md1Через Skills CLI (Vercel)
npx skills add NickCrew/Claude-Cortex --skill typescript-advanced-patterns -a gemini-cli2Командой платформы
gemini skills install https://github.com/NickCrew/Claude-Cortex --path skills/typescript-advanced-patternsВручную: положить файлы
.devin/skills/typescript-advanced-patterns/SKILL.mdСтарый путь .windsurf/skills/ тоже читается
Через Skills CLI (Vercel)
npx skills add NickCrew/Claude-Cortex --skill typescript-advanced-patterns -a opencodeClaude.ai
Упакуйте папку в zip и загрузите в Settings → Capabilities → Skills
По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов
Вопросы о typescript-advanced-patterns
Как установить typescript-advanced-patterns в Claude Code?
Выполните npx skills add NickCrew/Claude-Cortex --skill typescript-advanced-patterns -a claude-code. Файл скилла находится по пути ~/.claude/skills/typescript-advanced-patterns/SKILL.md.
Что делает typescript-advanced-patterns?
Помогает применять продвинутые возможности TypeScript для API и сложных моделей предметной области. Даёт справки по типам, проверкам и типобезопасным паттернам.
Какие темы TypeScript охватывает скилл?
Среди тем — условные и отображаемые типы, type guards, дискриминируемые объединения, брендированные типы, обобщения и вывод типов. Для каждой темы есть отдельный файл в references.
Исходный текст
SKILL.md · MIT
---
name: typescript-advanced-patterns
description: Advanced TypeScript patterns for type-safe, maintainable code using sophisticated type system features. Use when building type-safe APIs, implementing complex domain models, or leveraging TypeScript's advanced type capabilities.
keywords:
- TypeScript
- advanced types
- branded types
- conditional types
- discriminated union
- generic constraints
- mapped types
- template literal types
- type guard
- type inference
file_patterns:
- '**/*.ts'
- '**/*.tsx'
- '**/package.json'
- '**/tsconfig.json'
confidence: 0.78
---
# TypeScript Advanced Patterns
Expert guidance for leveraging TypeScript's advanced type system features to build robust, type-safe applications with sophisticated type inference, compile-time guarantees, and maintainable domain models.
## When to Use This Skill
- Building type-safe APIs with strict contracts and validation
- Implementing complex domain models with compile-time enforcement
- Creating reusable libraries with sophisticated type inference
- Enforcing business rules through the type system
- Building type-safe state machines and builders
- Developing framework integrations requiring advanced types
- Implementing runtime validation with type-level guarantees
## Core Concepts
TypeScript's type system enables compile-time safety through:
1. **Conditional Types**: Type selection based on conditions (type-level if/else)
2. **Mapped Types**: Transform object types systematically (Partial, Readonly, Pick, Omit)
3. **Template Literal Types**: String manipulation at compile time
4. **Type Guards**: Runtime checking with type narrowing (`value is Type`)
5. **Discriminated Unions**: Type-safe state machines with exhaustiveness checking
6. **Branded Types**: Nominal types for preventing primitive mixing
7. **Builder Pattern**: Type-safe fluent APIs with progressive type constraints
8. **Advanced Generics**: Constraints, inference, and higher-kinded type patterns
9. **Utility Types**: Deep transformations and compositions
10. **Type Inference**: Const assertions and contextual typing
## Quick Reference
Load detailed references on-demand:
| Topic | Reference File |
|-------|----------------|
| Conditional Types | `skills/typescript-advanced-patterns/references/conditional-types.md` |
| Mapped Types | `skills/typescript-advanced-patterns/references/mapped-types.md` |
| Template Literal Types | `skills/typescript-advanced-patterns/references/template-literal-types.md` |
| Type Guards | `skills/typescript-advanced-patterns/references/type-guards.md` |
| Discriminated Unions | `skills/typescript-advanced-patterns/references/discriminated-unions.md` |
| Branded Types | `skills/typescript-advanced-patterns/references/branded-types.md` |
| Builder Pattern | `skills/typescript-advanced-patterns/references/builder-pattern.md` |
| Advanced Generics | `skills/typescript-advanced-patterns/references/advanced-generics.md` |
| Utility Types | `skills/typescript-advanced-patterns/references/utility-types.md` |
| Type Inference | `skills/typescript-advanced-patterns/references/type-inference.md` |
| Decorators | `skills/typescript-advanced-patterns/references/decorators.md` |
| Performance Best Practices | `skills/typescript-advanced-patterns/references/performance-best-practices.md` |
| Common Pitfalls | `skills/typescript-advanced-patterns/references/common-pitfalls.md` |
| Testing Types | `skills/typescript-advanced-patterns/references/testing-types.md` |
## Implementation Workflow
### 1. Identify Pattern Need
- Analyze type safety requirements
- Identify runtime vs compile-time constraints
- Choose appropriate pattern from Quick Reference
### 2. Load Reference
- Read specific reference file for pattern
- Review examples and use cases
- Understand trade-offs
### 3. Implement Pattern
- Start simple, add complexity as needed
- Use strict mode (`tsconfig.json` with `"strict": true`)
- Test with type assertions
### 4. Validate
- Ensure type errors caught at compile time
- Verify runtime behavior matches types
- Check performance (avoid excessive type complexity)
### 5. Document
- Add JSDoc comments for public APIs
- Document type constraints and assumptions
- Provide usage examples
## Common Mistakes to Avoid
1. **Using `any` instead of `unknown`**: Loses all type safety
- Use `unknown` and type guards instead
2. **Type assertions without validation**: Unsafe runtime behavior
- Prefer type guards (`value is Type`) over `as Type`
3. **Overusing generics**: Unnecessary complexity
- Only use generics when types truly vary
4. **Deep type nesting**: Slow compilation, hard to debug
- Keep types composable and shallow
5. **Forgetting `readonly`**: Accidental mutations
- Mark immutable data structures as `readonly`
6. **Not enabling strict mode**: Missing null checks and type errors
- Always use `"strict": true` in `tsconfig.json`
7. **Mixing type and interface incorrectly**: Confusing semantics
- Use `type` for unions/utilities, `interface` for object shapes
## Quick Patterns
### Type-Safe ID
```typescript
type UserId = string & { readonly __brand: 'UserId' };
function createUserId(id: string): UserId { return id as UserId; }
```
### Discriminated Union
```typescript
type State =
| { status: 'loading' }
| { status: 'success'; data: string }
| { status: 'error'; error: Error };
```
### Mapped Type Transformation
```typescript
type Readonly<T> = { readonly [P in keyof T]: T[P] };
type Partial<T> = { [P in keyof T]?: T[P] };
```
### Type Guard
```typescript
function isString(value: unknown): value is string {
return typeof value === 'string';
}
```
## Resources
- **TypeScript Handbook**: https://www.typescriptlang.org/docs/handbook/
- **Type Challenges**: https://github.com/type-challenges/type-challenges
- **ts-toolbelt**: Advanced type utilities library
- **zod**: Runtime validation with TypeScript inference
- **tsd**: Test TypeScript type definitions
© NickCrew · MIT · NickCrew/Claude-Cortex
Похожие скиллы
Все скиллы по теме «Языки программирования» →Сначала — typescript-advanced-patterns от других авторов.