narrow-react-prop-types
Что он делает
Этот скилл ведёт ИИ-агента в удалении необязательных пропсов, которые существуют только для тестовых или сторис-данных. Он нужен React-разработчикам, которым нужны строгие и точные типы компонентов.
Когда использовать
- ✓Когда пропсы компонента разрослись и стали необязательными только ради сторис или тестов.
- ✓Когда хотите убрать состояния, которые реальное приложение никогда не использует.
- ✓Когда переписываете типы React и хотите, чтобы они выводились из живого кода.
Ссылка на скилл
https://github.com/humanlayer/humanlayer/blob/main/.claude/skills/narrow-react-prop-types/SKILL.mdСкопируйте и вставьте её в ваш ИИ (Claude, ChatGPT или Cursor) с просьбой следовать инструкциям.
Как использовать
Самый простой способ: скопируйте сообщение и вставьте его в свой ИИ. Он прочитает скилл и выполнит инструкции.
Готовое сообщение для вставки
Для Claude Code, Codex или Cursor: запустите в папке проекта, и скилл установится.
Скачайте SKILL.md и положите его в папку скиллов вашего агента.
Пример запроса к вашему ИИ
“В этом React-компоненте карточки слишком много необязательных пропсов. Сузь типы до того, что реально использует приложение.”
5 новых скиллов в неделю. 1 минута чтения.
Как это работает
Агент сначала находит реальные места вызова вне тестов, затем приводит типы в соответствие с ними. Код тестов и сторис обновляется под более строгие типы.
Технический текст (оригинальный SKILL.md)
Оригинальный текст автора на английском, прямо с GitHub.
Narrow React Prop Types
Use this skill when a React component's props have been widened for stories, mocks, tests, or demos and now express states the live application does not enter.
The goal is to make component types describe the real live-code-path contract, then require stories/tests/mocks to adapt to that contract instead of weakening it.
Core Requirements
- Find the actual non-test, non-Storybook call sites before changing types.
- Treat live code paths as the source of truth for the prop contract.
- Do not preserve optional props only because they make Storybook, tests, or mock data easier.
- Keep props optional only when there are non-Storybook, non-test call sites which do not provide them and which have a good reason for not doing so.
- Types should not enable expressing states which are not observed in non-test, non-Storybook call sites.
- Types should be as strict as possible so code can be as simple as possible.
- Prefer deriving and extracting types from existing live-code-path values and APIs where possible.
Workflow
1. Identify the suspect component
Look for components with these signals:
- Large props interfaces with many optional fields.
- Optional callback calls such as
onSelect?.(...)oronArchive?.(...). - Fallback state handling such as
items ?? [],count ?? 0, orhandler && ...around values live code likely always supplies. - UI affordances that always render even though their callbacks are optional.
- Props that look demo-oriented, such as
defaultFoo, alternate handler shapes, or display toggles not used by live code.
Do not pick a target from a story or test alone. Use stories/tests only as supporting evidence that the type has been widened, not as evidence that a state is real.
2. Find every live usage
Search for all imports/usages of the component, exported prop type, and shared child primitives.
Classify call sites by whether they are live code paths or support code:
- Live code paths: app routes, wired components, providers, hooks, production package exports, and shared components used by those paths.
- Support code: Storybook stories, test files, fixtures, mocks, demo harnesses, and visual-only examples.
Only live code paths should determine what the component API supports.
3. Derive the real types from the live code paths
Read the live call sites and classify each prop:
- Required: every non-test, non-Storybook call site supplies it.
- Optional: at least one non-test, non-Storybook call site omits it and that omission is a meaningful runtime state.
- Removed: no non-test, non-Storybook call site uses it.
Nullability and optionality are different. If live code always passes a prop but the value can be empty, prefer a required nullable prop such as focusedItem: FocusedItem | null over focusedItem?: FocusedItem | null.
4. Tighten the public prop type
Update exported prop types to match only the states observed in live code paths.
The looser and more optional a type is, the more possible states the component has to reason about. Every optional prop creates another branch the component must handle, test, and keep correct. Prefer strict types that prevent impossible states instead of broad types that require defensive render logic.
If the component always renders an interactive affordance, require the handler that makes it work. Do not allow inert states like a visible menu item that calls onRename?.(...).
5. Derive and extract types where possible
Prefer deriving types from the live APIs instead of restating them manually:
Parameters<typeof fn>[0]for function argument types.ReturnType<typeof fn>for return types.Extract<Union, Shape>for narrowing a union to a real variant.React.Dispatch<React.SetStateAction<T>>for React state setters instead of approximating them as(value: T) => void.
Prefer explicit state type parameters when inference would widen or obscure the intended state shape:
const [dialogState, setDialogState] = useState<DialogState>({
id: null,
isOpen: false,
})
Avoid relying on implicit useState(...) inference when it produces broad nullable object shapes, string literal widening, or callback types that later need hand-written approximations.
6. Tighten internal child props too
Do not stop at the exported component if it passes broad props into child primitives.
If row/menu/button child components receive optional handlers only because the parent props were
Частые вопросы
Не сломает ли это мои тесты?
Тесты и сторис могут потребовать обновления: скилл адаптирует их под более строгие типы, а не ослабляет типы.
Проверяет ли он сначала реальное приложение?
Да. Он находит реальные места вызова вне тестов до того, как менять типы.
Могут ли какие-то пропсы остаться необязательными?
Да, но только если реальное место вызова их не передаёт и есть веская причина.
Подробности
Оригинальное описание автора
narrow React component prop types to match live code paths
repo: humanlayer/humanlayer
Популярность
- Звёзды на GitHub
- 13k
- Место в рейтинге
- #11388
- Лицензия
- Apache-2.0
- Обновлён
- 31.10.2026
Комментарии
- …
Другие скиллы из этого репозитория
asd-ste100
13kУчит агента переписывать запутанный английский в короткие предложения с одним смыслом, которые легко читать и людям, и другим программам.
better-github-skill
13kПомогает агенту проверить статус pull request, прочитать комментарии ревью и найти причину падения сборки CI с помощью готовых скриптов GitHub.
calldiff
13kПомогает агенту сравнить цепочки вызовов функций в кодовой базе между двумя версиями git, чтобы ревью кода показывало, какое поведение изменилось.
chrome-devtools-cli
13kПозволяет агенту управлять Chrome из терминала: открывать страницы, нажимать кнопки, заполнять формы и делать снимки страниц для автоматизации и тестов.
Похожие скиллы
angular-developer
280kПомогает агенту писать код на Angular и советовать по структуре проекта. Полезен для новых проектов, создания частей кода и улучшения производительности.
frontend-a11y
280kПомогает агенту делать веб-интерфейсы доступными для всех, чтобы сайты и приложения работали с программами чтения с экрана и клавиатурой.
frontend-patterns
280kАгент применяет современные паттерны фронтенд-разработки: оптимизирует производительность, управляет состоянием и следует практикам React и Next.js.