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

typescript-rules — скилл для Claude Code: правила React/TypeScript

Набор правил для фронтенд-разработки на React и TypeScript: типобезопасность, устройство компонентов, владение состоянием и обработка ошибок.

MIT ★ 720 обновлён 2026-10-29

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

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

Скилл задаёт правила для кода на TypeScript и React: какие типы использовать на границах с внешним API, localStorage и параметрами URL, когда допустим any и как его ограничить адаптером. Отдельно описаны сигналы для ревью сложных типов — число пропсов, глубина вложенности, количество type assertion.

Внутри — рекомендации по функциональным компонентам и хукам, границе сервер/клиент для фреймворков с RSC (с директивой "use client"), владению состоянием и обработке ошибок через Error Boundary, кастомные хуки и API-слой. Есть раздел про производительность: когда включён React Compiler, ручные React.memo, useMemo и useCallback добавляются только под измеренное узкое место.

Правила server/client-границы применяются только в проектах с серверными компонентами, в остальных их скилл предлагает пропускать.

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

  • выбрать между any, unknown и generics на границе с внешним API
  • определить, когда компонент пора разбивать по числу или вложенности пропсов
  • расставить обработку ошибок между Error Boundary, хуками и API-слоем
  • решить, нужны ли ручные useMemo/useCallback при включённом React Compiler
  • провести границу "use client" в проекте с серверными компонентами

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

  • Проверь типизацию компонента UserCard по правилам typescript-rules
  • Разбей этот компонент по сигналам сложности типов из typescript-rules
  • Расставь обработку ошибок в хуке useFetchUser по правилам typescript-rules

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

1Через Skills CLI (Vercel)

npx skills add shinpr/claude-code-workflows --skill typescript-rules -a claude-code

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

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

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

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

Вопросы о typescript-rules

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

Выполните npx skills add shinpr/claude-code-workflows --skill typescript-rules -a claude-code, скилл появится в ~/.claude/skills/typescript-rules/SKILL.md.

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

Он задаёт правила React/TypeScript-разработки: типобезопасность, устройство компонентов, владение состоянием, обработку ошибок и производительность. Применяется при работе с компонентами React, кодом на TypeScript и фронтенд-фичами.

Подходит ли typescript-rules для проектов без серверных компонентов?

Да, правила границы сервер/клиент с директивой "use client" скилл применяет только во фреймворках с серверными компонентами и пропускает их в остальных проектах.

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

SKILL.md · MIT
---
name: typescript-rules
description: React/TypeScript frontend development rules including type safety, component design, state management, and error handling. Use when implementing React components, TypeScript code, or frontend features.
---

# TypeScript Development Rules (Frontend)

## Comment Writing Rules

Code first: names and types carry meaning; a comment must add what code cannot, and one comment per decision is enough.

- Explain why a component memoizes, guards, or re-renders, not what the JSX renders.
- Record decisions and rationale; leave chronological history to version control.

## Type Safety

**Default Rule**: Prefer `unknown`, generics, or union types over `any`. Retain `any` only when an existing external, generated, or legacy public signature requires it, or when replacing it prevents the project type check from expressing a safe generic relationship. Record the declaration path or type-check result that proves the constraint. When a local adapter can preserve compatibility and expose a safer type within the user request or current task/design artifact, implement the adapter; otherwise confine `any` to the smallest adapter or public-signature boundary, document the reason, and validate untrusted data before it enters typed application code.

**Frontend Boundaries**

- React Props/State: use the declared application types.
- External API responses: treat unvalidated payloads as `unknown` and validate at the boundary. A generated client may retain its declared type when it also enforces the contract at runtime.
- `localStorage` / `sessionStorage`: handle `string | null`; treat parsed data as `unknown` until validated.
- URL parameters: handle the router or platform's nullable string shape, then parse and validate before converting to a domain type.
- Exported APIs and important boundaries: declare return types; allow inference for local implementations when the contract remains clear.

**Type Complexity Review Signals**

Use these as review prompts, not pass/fail thresholds. Existing project conventions and the component's responsibility take precedence.

- Props count: review ownership or splitting above 10.
- Optional props: review defaults or ownership when more than half are optional.
- Nested prop structures: review flattening beyond 2 levels.
- Type assertions: review the boundary when 3+ assertions are required.
- External API types: represent the actual external shape and convert at the application boundary.

## Coding Conventions

**Component and File Decisions**

- Prefer function components and Hooks for new code. Preserve working class components unless the accepted work requires migration; a class remains valid for an Error Boundary implementation.
- Reuse logic through the repository's established component, hook, or module pattern.
- Follow the project's adopted component architecture and file layout. Co-locate files only when it is established or approved as a new structure.

**Server/Client Boundary — only for RSC frameworks**

- Fetch and render on the server by default; isolate interactivity behind the smallest `"use client"` boundary that needs it.
- Keep browser-only APIs and event handlers inside client components.
- Skip these rules when the project has no server-component runtime.

**State Ownership**

- Preserve the repository's existing local, shared, and server-state ownership boundaries.
- Introduce Context, a shared-state layer, or a server-state dependency only when the accepted design requires ownership or lifecycle that the existing boundary cannot represent.
- Keep one authoritative owner for each state value and use immutable updates required by React change detection.

**Function and Props Boundaries**

- Prefer 0-2 parameters. For 3+ related values, use an object when it clarifies names or represents one domain input; preserve positional parameters when the repository convention or external API requires them.
- Declare component dependencies through typed props, hooks, Context, or injected modules according to the repository's established state and dependency boundaries.

**Environment Variables**

- Read client-side environment variables through the project's bundler accessor and public prefix.
- Validate required values through the repository's typed config layer; add a default only for an optional value or an explicitly defined local-development mode.

**Client Security**

- Keep credentials and secrets on the server; browser-delivered code and public environment variables are observable by clients.
- Exclude local environment files from version control and keep error output free of sensitive values.

**Asynchronous Processing**

- Follow the repository's promise style; use `async`/`await` when it clarifies sequencing and error propagation.
- Handle event-handler and asynchronous failures at their owning boundary. Error Boundaries cover descendant rendering failures, not ordinary callbacks or asynchronous work.
- Guard effect-driven requests against stale or post-unmount updates through the repository's cancellation or server-state mechanism.

**Formatting**

- Follow the repository's formatter, naming, module-resolution, and package-boundary configuration.
- Use an import alias only when the project configuration resolves it.

## Error Handling

Every caught error has one intentional outcome: propagate it, convert it to the repository's typed boundary result, or represent it as user-facing error state. Preserve context and log once at the boundary that owns diagnosis or recovery, with sensitive data redacted.

- Error Boundary: place it where descendant render failures have a defined UI recovery outcome.
- Custom Hook: preserve the application's existing error contract.
- API Layer: convert transport failures to the repository's established domain or boundary representation.
- Event handlers and async workflows: use the owning layer's exception, result, or UI-state contract.

## Performance Optimization

- When React Compiler is enabled, rely on it. Add manual `React.memo`, `useMemo`, or `useCallback` only for a measured bottleneck or a required stable identity at an external API/effect boundary.
- Apply code splitting or import changes when a configured bundle budget regresses, or when the accepted task names bundle size as an outcome and a repository bundle report attributes the relevant increase to the changed import. Follow the repository's existing loading pattern and verify the same signal after the change.

## Non-functional Requirements

- **Browser Compatibility**: Implement against the support policy in the PRD, Design Doc, Browserslist, or build configuration. When none is defined, preserve the repository's current transpilation/polyfill baseline and surface any new browser-dependent API as an unresolved compatibility decision.
- **Performance**: Verify against project-defined budgets and the metric representing the affected experience. When no budget exists, measure the changed path and report the observed result instead of inventing a threshold.

© shinpr · MIT · shinpr/claude-code-workflows

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

Все скиллы по теме «Фронтенд и UI» →
typescript-react-patterns agent-skills Скилл typescript-react-patterns для Claude Code: 33 правила типизации React на TypeScript — пропсы, хуки, события, refs, дженерики и контекст. Подключается, когда агент пишет компоненты и работает с типами. CX Codex +1 1 100установок typescript-react-cursorrules-prompt-file PatrickJS Правило typescript-react-cursorrules-prompt-file для Cursor задаёт стандарты функциональных компонентов React и TypeScript, типизации и структуры каталогов src/. CX Codex +1 ★ 41 178звёзд репо typescript-review metabase Скилл typescript-review для Claude Code проверяет изменения в TypeScript и JavaScript по правилам Metabase. Разбирает pull request и diff с фронтенд-кодом. CX Codex +1 2 300установок nextjs-typescript-tailwindcss-supabase Mindrally Скилл nextjs-typescript-tailwindcss-supabase задаёт агенту правила для Next.js 14, TypeScript, TailwindCSS и Supabase: серверные компоненты, обработка ошибок, читаемый код. CX Codex +1 1 400установок mastering-typescript Richard Hightower Скилл mastering-typescript помогает писать строгий код на TypeScript 5.9+ и настраивать тулчейн для React 19 или NestJS 11. Пригодится при миграции с JavaScript и проектировании сложных типов. CX Codex +1 821установок typescript-refactor pproenca Скилл typescript-refactor для Claude Code проверяет TypeScript и React-код на типобезопасность, убирает as и переводит на возможности TS 5.x–6.0. Включается при рефакторинге, типизации хуков и миграции. CX Codex +1 808установок

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

Весь набор →
testing-principles Скилл testing-principles для Claude Code задаёт правила выбора и оформления тестов независимо от языка стека. Включается при написании новых тестов, проверке их качества и выборе между unit-, integration- и E2E-уровнями. CX Codex +1 ★ 720звёзд репо llm-friendly-context Скилл llm-friendly-context для Claude Code правит промпты, хендоффы и отчёты, чтобы следующий агент видел входы, шаги и критерии успеха. CX Codex +1 ★ 720звёзд репо requirement-convergence Скилл requirement-convergence для Claude Code отделяет целевой результат изменений от предложенных требований и фиксирует исключения пользователя. Включается на этапе сбора требований до проектирования архитектуры. CX Codex +1 ★ 720звёзд репо work-planner Субагент work-planner для Claude Code превращает утверждённые Design Doc в план реализации с задачами, зависимостями и проверками. Запускается при запросе плана работ или планирования задач. CX Codex ★ 720звёзд репо documentation-criteria Скилл documentation-criteria для Claude Code определяет, какие документы нужны изменению и где их хранить. Агент подключает его при выборе объёма документации или создании и проверке технического документа. CX Codex +1 ★ 720звёзд репо codebase-analyzer Субагент codebase-analyzer для Claude Code собирает факты о кодовой базе перед составлением Design Doc. Запускается по утверждённому PRD или списку требований для оценки повторного использования и рисков. CX Codex ★ 720звёзд репо code-verifier Субагент code-verifier для Claude Code сверяет утверждения в PRD, дизайн-документах и планах работ с кодом репозитория. Его запускают перед ревью документа, после реализации или для проверки описания существующей системы. CX Codex ★ 720звёзд репо scope-discoverer Субагент scope-discoverer разбирает кодовую базу на функциональные блоки и связи для обратного документирования. Помогает подготовить фундамент под PRD. CX Codex ★ 720звёзд репо

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

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