如何用JSDoc正确文档化含剩余参数的解构函数参数?
正确文档化React剩余props组件的JSDoc写法
问题根源
你之前的JSDoc错误地将解构后的剩余参数...props标注为父对象的子属性(footerProps.props),这导致TypeScript错误识别props的类型为{ props: any },而非剩余属性的集合,进而触发解构时的类型报错。
解决方案1:使用@typedef定义完整props类型
通过@typedef提前定义组件的props结构,明确固定属性和剩余属性的类型,可读性更强:
/** * @typedef {Object} CartFooterProps * @property {Object} classes - 父组件传入的样式类 * @property {Object} events - 组件的事件集合 * @property {React.ReactNode} children - 子组件内容 * @property {Record<string, any>} [rest] - 剩余的任意props(可替换为更具体的类型) */ /** * CartFooter 组件 * @type {React.FunctionComponent<CartFooterProps>} * @param {CartFooterProps} props - 组件属性 * @param {React.Ref<Object>} ref - 组件引用 * @returns {JSX.Element} */ const CartFooter = ({ classes: parentClasses, events, children, ...props }, ref) => { // 此处可正常解构props中的属性 const { a, b, ...options } = props; const { c, d } = options; // 组件逻辑... return <footer ref={ref}>{children}</footer>; };
解决方案2:直接在参数标注中定义剩余属性类型
如果不需要单独的类型别名,可直接在@param中用索引签名声明剩余属性:
/** * CartFooter 组件 * @type {React.FunctionComponent} * @param {{ * classes: Object; * events: Object; * children: React.ReactNode; * [key: string]: any; * }} props - 组件属性,包含固定属性和剩余任意属性 * @param {React.Ref<Object>} ref - 组件引用 * @returns {JSX.Element} */ const CartFooter = ({ classes: parentClasses, events, children, ...props }, ref) => { const { a, b, ...options } = props; const { c, d } = options; // 组件逻辑... return <footer ref={ref}>{children}</footer>; };
注意事项
- 移除不必要的
@constructor标签:函数组件并非构造函数,React.FunctionComponent已明确组件类型。 - 剩余属性的类型尽量具体化:如果知道剩余props的具体结构,替换
any或Record<string, any>为实际类型,提升类型检查的准确性。
内容的提问来源于stack exchange,提问作者Artemios Antonio Balbach
相关产品推荐
相关产品推荐

