You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JSDoc改写这段React组件的TypeScript类型定义代码?

要把这段TypeScript代码转换成JSDoc注释形式,按以下步骤操作:

1. 转换ButtonProps接口

用JSDoc的@typedef结合类型交叉语法,模拟TypeScript的接口继承与属性扩展:

/**
 * 整合原生按钮属性、变体属性与自定义属性的Button组件Props类型
 * @typedef {React.ButtonHTMLAttributes<HTMLButtonElement> & VariantProps<typeof buttonVariants> & { asChild?: boolean }} ButtonProps
 */

注:如果VariantProps是外部模块导出的类型,需在JSDoc中补全模块引用,比如import('./path-to-variants').VariantProps

2. 标注forwardRef组件

针对React.forwardRef,用JSDoc的模板(@template)、参数和返回值注释,明确泛型类型:

/**
 * 创建带Ref的Button组件
 * @template {HTMLButtonElement} T - 按钮DOM元素的类型
 * @param {React.ForwardRefRenderFunction<T, ButtonProps>} renderFn - 组件渲染函数
 * @returns {React.ForwardRefExoticComponent<React.PropsWithoutRef<ButtonProps> & React.RefAttributes<T>>}
 */
const Button = React.forwardRef((props, ref) => {
  // 这里编写你的组件逻辑
});

完整代码示例

/**
 * @typedef {React.ButtonHTMLAttributes<HTMLButtonElement> & VariantProps<typeof buttonVariants> & { asChild?: boolean }} ButtonProps
 */

/**
 * @template {HTMLButtonElement} T
 * @param {React.ForwardRefRenderFunction<T, ButtonProps>} renderFn
 * @returns {React.ForwardRefExoticComponent<React.PropsWithoutRef<ButtonProps> & React.RefAttributes<T>>}
 */
const Button = React.forwardRef((props, ref) => {
  // 组件实现
});

内容的提问来源于stack exchange,提问作者Garth Trickett

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 06:07:40