如何用JSDoc为React高阶组件组合的组件添加类型标注以获代码提示?
解决JSDoc标注高阶组件withLoader的泛型问题
要让包装后的组件获得正确的代码补全,需要完整标注泛型的传递链路,同时使用React标准类型来定义组件。以下是修正后的代码和关键说明:
1. 先定义必要的类型(如果未定义)
/** * @typedef {object} LoadingCardProps * @property {string} message - 加载提示文本 */ /** * @typedef {object} WithLoaderProps * @property {boolean} isLoading - 控制加载状态的开关 */
2. 修正withLoader的JSDoc标注
/** * 创建带加载状态的高阶组件 * @param {LoadingCardProps} config - LoadingCard的配置参数 * @returns {<P>(Component: React.ComponentType<P>) => React.ComponentType<P & WithLoaderProps>} 接收目标组件并返回包装后的组件 */ export const withLoader = (config) => { /** * @template P * @param {React.ComponentType<P>} Component - 要包装的目标组件 * @returns {React.ComponentType<P & WithLoaderProps>} 包装后的组件,支持原组件Props + isLoading */ const DecoratedComponent = (Component) => { /** * @param {P & WithLoaderProps} props - 组合后的Props:原组件Props + isLoading * @returns {React.ReactNode} */ const ComponentWithLoader = (props) => { if (props.isLoading) { return <LoadingCard {...config} />; } // 解构移除isLoading,避免传递给不需要该属性的原组件 const { isLoading, ...restProps } = props; return <Component {...restProps} />; }; return ComponentWithLoader; }; return DecoratedComponent; };
3. 关键修正点
- 使用标准React类型:用
React.ComponentType<P>替代自定义的ReactComponent<P>,编辑器能正确识别函数/类组件类型。 - 顶层泛型标注:在
withLoader的返回类型中明确泛型函数结构<P>(...) => ...,确保泛型P从接收组件到返回组件的传递链完整。 - 内部泛型关联:
DecoratedComponent的@template P与返回类型的泛型对应,让JSDoc能追踪类型传递。 - props清理:解构移除
isLoading后再传递给原组件,避免不必要的props警告。
4. 使用示例(无需额外修改)
/** * @typedef {object} LoadedComponentProps * @property {string} content - 组件显示内容 */ /** * @param {LoadedComponentProps} props * @returns {React.ReactNode} */ const LoadedComponent = ({ content }) => { return <div>{content}</div>; }; // 此时DecoratedLoadedComponent会自动提示content(string)和isLoading(boolean)两个props const DecoratedLoadedComponent = withLoader({ message: 'Wait a bit, things are loading...' })(LoadedComponent);
内容的提问来源于stack exchange,提问作者Diego Bevilaqua
相关产品推荐
相关产品推荐

