К основному содержанию
скилл CX Codex

typescript-patterns — скилл для Claude Code: что делает и установка

Скилл typescript-patterns учит ИИ-агента сложным приёмам TypeScript в строгом режиме. Он помогает избежать сбоев во время выполнения за счёт проверок на этапе сборки.

MIT 202 установок ★ 29 обновлён 2026-08-17

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add oakoss/agent-skills --skill typescript-patterns -a claude-code
Открыть на GitHub

Что делает typescript-patterns

Скилл задаёт агенту строгие правила TypeScript и отучает использовать небезопасный тип any. Вместо него модель применяет сужение через unknown и предикаты is. Внутри описаны техники работы с дженериками, размеченными объединениями, оператором satisfies и утилитой NoInfer.

Этот набор не обучает базовому синтаксису. Инструкций по миграции с чистого JavaScript или настройке сборщиков тут тоже нет. Скилл рассчитан на работу с жёсткими флагами вроде noUncheckedIndexedAccess. Если вам требуется лишь собрать проект или написать первый интерфейс, скилл не сработает, так как он ориентирован на строгую систему типов.

Какие задачи решает

  • Устранить использование any через безопасное сужение типов
  • Настроить исчерпывающую проверку вариантов объединения с помощью never
  • Сохранить точные литеральные типы через оператор satisfies
  • Ограничить параметры дженериков конструкцией extends

Примеры запросов агенту

  • Перепиши функцию разбора ответа API без использования any и настрой сужение типов
  • Сделай объединение типов для статусов заказа и добавь проверку исчерпываемости через never
  • Замени приведение через as на оператор satisfies, чтобы сохранить точные литералы

Как установить typescript-patterns

1Через Skills CLI (Vercel)

npx skills add oakoss/agent-skills --skill typescript-patterns -a claude-code

2Вручную: положить файлы

~/.claude/skills/typescript-patterns/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/typescript-patterns/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о typescript-patterns

Как установить typescript-patterns в Claude Code?

Выполните в терминале команду npx skills add oakoss/agent-skills --skill typescript-patterns -a claude-code.

Что делает скилл typescript-patterns?

Он снабжает агента сводом правил для строгого TypeScript, включая работу с дженериками, условными типами и безопасным сужением структур данных.

Для каких задач этот скилл не предназначен?

Скилл не объясняет основы языка, не содержит инструкций по миграции с JavaScript и не помогает конфигурировать сборку проекта.

Исходный текст

SKILL.md · MIT
---
name: typescript-patterns
description: 'Advanced TypeScript patterns for strict mode development. Covers type utilities (Pick, Omit, Partial, Record, Awaited), generics with constraints and inference, type guards and narrowing, discriminated unions, conditional and mapped types, template literal types, const assertions, satisfies operator, module patterns, and modern JavaScript idioms (eslint-plugin-unicorn). Use when building type-safe APIs, preventing runtime errors through types, working with strict TypeScript configuration, debugging complex type errors, or enforcing modern JS idioms. Use for generics, type guards, utility types, strict mode, type inference, narrowing, type safety, const assertions, satisfies, module augmentation, unicorn, for-of, modern-js.'
license: MIT
metadata:
  author: oakoss
  version: '1.1'
  source: 'https://www.typescriptlang.org/docs/'
user-invocable: false
---

# TypeScript Patterns

## Overview

Advanced TypeScript patterns that use the type system to prevent runtime errors. Focuses on strict mode TypeScript with patterns for type inference, narrowing, and compile-time validation. **Not** a beginner tutorial.

**When to use:** Building type-safe APIs, complex data transformations, library authoring, preventing runtime errors through types, working with strict mode flags.

**When NOT to use:** Learning TypeScript basics (primitives, interfaces, classes), JavaScript-to-TypeScript migration guidance, tooling setup, or build configuration.

## Quick Reference

| Pattern               | API                                  | Key Points                           |
| --------------------- | ------------------------------------ | ------------------------------------ |
| Utility types         | `Pick<T, K>`, `Omit<T, K>`           | Extract or exclude properties        |
| Partial/Required      | `Partial<T>`, `Required<T>`          | Make properties optional or required |
| Record type           | `Record<K, V>`                       | Object with known keys               |
| Awaited type          | `Awaited<T>`                         | Unwrap Promise return types          |
| ReturnType/Parameters | `ReturnType<F>`, `Parameters<F>`     | Extract function types               |
| Generic constraints   | `<T extends Type>`                   | Constrain generic parameters         |
| Type inference        | `type Inferred = typeof value`       | Let TypeScript infer from values     |
| Type guards           | `typeof`, `instanceof`, `in`         | Narrow types at runtime              |
| Custom type guards    | `(x): x is Type`                     | User-defined narrowing functions     |
| Inferred predicates   | `(x) => x !== null`                  | Auto-inferred type predicate filters |
| Discriminated unions  | Union with literal `type` property   | Exhaustive pattern matching          |
| Conditional types     | `T extends U ? X : Y`                | Type-level conditionals              |
| Mapped types          | `{ [K in keyof T]: T[K] }`           | Transform all properties             |
| Template literals     | `` `${A}-${B}` ``                    | String literal type manipulation     |
| Const assertions      | `as const`                           | Narrowest possible literal types     |
| Satisfies operator    | `value satisfies Type`               | Type check without widening          |
| NoInfer utility       | `NoInfer<T>`                         | Prevent inference from a position    |
| Const type params     | `<const T extends Type>`             | Narrow inference without `as const`  |
| Inline type imports   | `import { type User }`               | Import types explicitly              |
| Module augmentation   | `declare module 'lib' { ... }`       | Extend third-party types             |
| Assertion functions   | `function assert(x): asserts x is T` | Throw if type guard fails            |

## Common Mistakes

| Mistake                              | Correct Pattern                                |
| ------------------------------------ | ---------------------------------------------- |
| Using `any` without justification    | Use `unknown` and narrow with type guards      |
| Manual type assertions everywhere    | Let inference work, type function returns      |
| Destructuring before type narrowing  | Keep object intact for discriminated unions    |
| Index access without undefined check | Enable `noUncheckedIndexedAccess`              |
| `as Type` casting unsafe values      | Use `satisfies Type` to preserve narrow types  |
| Inline objects in generics           | Extract to `const` or type alias               |
| Omitting `extends` in constraints    | Always constrain generics when possible        |
| Using `Parameters<typeof fn>[0]`     | Type the parameter directly in function        |
| Not handling union exhaustiveness    | Use `never` checks in switch/if-else           |
| `value as const satisfies Type`      | Use `satisfies Type` then `as const` if needed |

## Delegation

- **Pattern discovery**: Use `Explore` agent to find existing patterns in codebase
- **Type error debugging**: Use `Task` agent for multi-step type resolution
- **Code review**: Delegate to `code-reviewer` skill for type safety audit

## References

- [Type utilities (Pick, Omit, Partial, Required, Record, Extract, Exclude, ReturnType, Parameters, Awaited)](references/type-utilities.md)
- [Generics (constraints, inference, default parameters, variance)](references/generics.md)
- [Type guards and narrowing (typeof, instanceof, in, custom guards, assertion functions)](references/type-guards.md)
- [Discriminated unions (exhaustive checking, never type, tagged unions)](references/discriminated-unions.md)
- [Conditional types (distributive conditionals, infer keyword, type-level logic)](references/conditional-types.md)
- [Mapped types (key remapping, template literals, modifiers)](references/mapped-types.md)
- [Strict mode patterns (noUncheckedIndexedAccess, exactOptionalPropertyTypes, const assertions, satisfies)](references/strict-mode.md)
- [Module patterns (inline type imports, declaration files, module augmentation, ambient types)](references/module-patterns.md)
- [Modern idioms (eslint-plugin-unicorn patterns, modern array/string/DOM APIs, ES modules)](references/modern-idioms.md)

© oakoss · MIT · oakoss/agent-skills

Похожие скиллы

Все скиллы по теме «Языки программирования» →
typescript-strict-migrator patricio0312rev Скилл typescript-strict-migrator для Claude Code переводит TypeScript-проект на strict по одному флагу после аудита ошибок. Миграция начинается с noImplicitAny, затем включает strictNullChecks и остальные флаги. CX Codex +1 280установок typescript-development sammcj Скилл typescript-development активирует строгую типизацию и лучшие практики TypeScript в Claude Code. Автоматически применяет правила кода для проектов на TypeScript и JavaScript. CX Codex +1 ★ 173звёзд репо typescript gentleman-programming Задаёт строгие паттерны TypeScript: константные типы, плоские интерфейсы, тайпгарды. Включается, когда агент пишет типы, интерфейсы или дженерики. CX Codex +1 500установок typescript-magician mcollina Скилл typescript-magician устраняет ошибки TypeScript, заменяет any на строгие типы и строит типобезопасные дженерики. Помогает навести порядок в типах кодовой базы. CX Codex +1 3 000установок typescript-pro VoltAgent Community Субагент typescript-pro для Claude Code работает со сложными типами, generic-ами и типобезопасностью frontend и backend. Включается для типизации крупных модулей. CX Codex 9 602установок typescript-advanced-patterns curiositech Скилл typescript-advanced-patterns помогает проектировать сложные типы TypeScript: от branded types и discriminated unions до Zod-инференса и exhaustive checking. CX Codex +1 148установок

Из того же набора106

Весь набор →
tanstack-form Помогает собирать формы на TanStack Form v1 в React и управлять их состоянием, валидацией и отправкой. Описывает работу со сложными и динамическими формами. CX Codex +1 222установок knowledge-graph-builder Скилл knowledge-graph-builder для Claude Code проектирует граф знаний, помогает выбрать графовую БД и связать обход графа с векторным поиском. Решает задачи Graph RAG и проверки фактов. CX Codex +1 222установок pino-logging Скилл pino-logging помогает настроить структурированные логи Pino в Node.js: от контекста запросов и маскировки секретов до вывода в разные места. CX Codex +1 217установок database-security Скилл database-security проверяет доступ к данным в Supabase, Postgres и Convex: покрытие RLS, дыры в политиках, аудит-логи. Пригодится перед релизом или при разборе инцидента. CX Codex +1 208установок react-patterns Скилл react-patterns по React 19+: паттерны хуков, выбор управления состоянием, загрузка данных через use() и борьба с лишними ре-рендерами. CX Codex +1 201установок ci-cd-architecture Скилл ci-cd-architecture помогает спроектировать CI/CD-пайплайн, выбрать платформу деплоя и настроить безопасность GitHub Actions. Пригодится при запуске и развитии проекта. CX Codex +1 199установок openapi Настраивает агента на проектирование спецификаций OpenAPI 3.1 и генерацию TypeScript-клиентов. Помогает писать схемы контрактов и документацию для REST API. CX Codex +1 197установок css-animation-patterns Скилл css-animation-patterns для Claude Code помогает создавать CSS-анимации без перерисовки макета. Описывает аппаратно ускоренные свойства, переходы и новые API движения. CX Codex +1 196установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой