SuperAPI AI 工具集

typescript-react-patterns

前端与建站

查看项目

更新于 10-13 20:08

技能介绍

用途

typescript-react-patterns 是一套 TypeScript 与 React 结合开发时的类型安全实践规则集,用于在编写带类型的 React 组件、Hooks、事件处理、Refs、泛型组件,以及配置带类型的 Context Provider 时提供指导,也可用于修复 React 代码中的 TypeScript 错误。

规则集包含 33 条规则,分布在 7 个类别中,版本为 2.0.0,采用 MIT 许可。

何时应用

  • 为 React 组件 props 添加类型标注
  • 使用 TypeScript 创建自定义 Hooks
  • 以正确的类型处理事件
  • 处理 Refs(DOM、可变值、命令式句柄)
  • 构建泛型、可复用的组件
  • 配置带类型的 Context Provider
  • 修复 React 代码中的 TypeScript 错误

规则分类与优先级

优先级 类别 影响 前缀
1 Component Typing CRITICAL comp-
2 Hook Typing CRITICAL hook-
3 Event Handling HIGH event-
4 Ref Typing HIGH ref-
5 Generic Components MEDIUM generic-
6 Context & State MEDIUM ctx-
7 Utility Types LOW util-

规则清单

1. Component Typing(CRITICAL)

  • comp-props-interface:props 使用 interface,联合类型使用 type
  • comp-children-types:正确标注 children(ReactNode、ReactElement)
  • comp-default-props:通过解构默认值设置默认 props
  • comp-forward-ref:为 forwardRef 组件标注类型
  • comp-polymorphic:多态 "as" prop 的类型标注
  • comp-fc-vs-function:函数声明与 React.FC 的对比
  • comp-display-name:用于调试的 display name
  • comp-rest-props:以正确类型展开 rest props

2. Hook Typing(CRITICAL)

  • hook-usestate:为 useState 使用合适的泛型类型
  • hook-useref:用于 DOM 元素与可变值的 useRef
  • hook-use-reducer:配合可辨识联合 action 的 useReducer
  • hook-use-callback:带类型参数的 useCallback
  • hook-use-memo:带类型返回值的 useMemo
  • hook-use-context:带空值检查的 useContext
  • hook-custom-hooks:自定义 Hook 的返回类型
  • hook-generic-hooks:泛型自定义 Hook

3. Event Handling(HIGH)

  • event-handler-types:事件处理器的类型模式
  • event-click-handler:点击事件的类型标注
  • event-form:表单事件处理(submit、change、select)
  • event-keyboard:键盘事件类型

4. Ref Typing(HIGH)

  • ref-dom-elements:为 useRef 指定具体 HTML 元素类型
  • ref-callback:用于 DOM 测量的回调 ref 模式
  • ref-imperative-handle:useImperativeHandle 的类型标注

5. Generic Components(MEDIUM)

  • generic-list:泛型列表组件
  • generic-select:泛型选择/下拉组件
  • generic-table:带类型列的泛型表格
  • generic-constraints:使用 extends 的泛型约束

6. Context & State(MEDIUM)

  • ctx-create:创建带类型的 Context
  • ctx-provider:带空值检查 Hook 的 Provider 模式
  • ctx-reducer:配合 useReducer 的 Context

7. Utility Types(LOW)

  • util-component-props:使用 ComponentPropsWithoutRef 获取 HTML props
  • util-pick-omit:使用 Pick、Omit、Partial 派生 props
  • util-discriminated-unions:用于状态机的可辨识联合

核心示例

组件 Props

interface ButtonProps {
  variant: 'primary' | 'secondary' | 'danger'
  size?: 'sm' | 'md' | 'lg'
  children: React.ReactNode
  onClick?: () => void
}

function Button({ variant, size = 'md', children, onClick }: ButtonProps) {
  return (
    <button className={`btn-${variant} btn-${size}`} onClick={onClick}>
      {children}
    </button>
  )
}

带空值检查的类型化 Context

interface AuthContextType {
  user: User | null
  login: (credentials: Credentials) => Promise<void>
  logout: () => void
}

const AuthContext = createContext<AuthContextType | null>(null)

function useAuth() {
  const context = useContext(AuthContext)
  if (!context) throw new Error('useAuth must be used within AuthProvider')
  return context
}

泛型组件

interface ListProps<T> {
  items: T[]
  renderItem: (item: T) => React.ReactNode
  keyExtractor: (item: T) => string
}

function List<T>({ items, renderItem, keyExtractor }: ListProps<T>) {
  return <ul>{items.map(item => <li key={keyExtractor(item)}>{renderItem(item)}</li>)}</ul>
}

使用方式

阅读各个规则文件以获取详细说明,例如:

  • rules/comp-props-interface.md
  • rules/hook-usestate.md
  • rules/event-form.md
  • rules/ref-dom-elements.md
  • rules/util-discriminated-unions.md

完整展开所有规则的指南见:AGENTS.md

参考资料

  • React TypeScript Cheatsheet
  • React + TypeScript Guide
  • TypeScript Handbook

限制

关于安装命令、具体运行方式、收费模式与适用平台,资料中暂未提供。