【问题标题】:Borrowing a JSDoc comment from external interface property从外部接口属性借用 JSDoc 注释
【发布时间】:2021-06-09 19:14:09
【问题描述】:

我正在开发一个 React 应用程序。您可能知道,很多时候我们希望子组件的 props 直接链接到父组件的状态。

因此,我在父类组件的状态接口中添加了以下文档。

// Parent.tsx

interface ParentState {
  /**
   * Stores the list of errors encountered during render.
   */
  errors: string[];
}

export function Parent extends React.Component<{}, ParentState> {
  // ...

  render () {
    return <Child errors={errors} />
  }
}

在单独文件中定义的子组件内,我希望ChildProps 接口共享相同的文档。

// Child.tsx

interface ChildProps {
  /**
   * How do I use the `ParentState.errors` definition?
   */
  errors: string[]
}

export function Child (props: ChildProps) {
  return <ul>{errors.map(error) => <li key={index}>error</li>}</ul>
}

我已经尝试使用 JSDoc @borrow module:Parent.ParentState.errors 标记,同时为 Parent 组件指定 @module Parent。我不知道如何链接这两个文档。无论我尝试什么,孩子道具的文档都不会显示在 VSCode 智能感知中。

我的问题是:如何从外部接口属性借用文档?

【问题讨论】:

    标签: reactjs typescript jsdoc


    【解决方案1】:

    @inheritdoc 尚不支持,但可以选择使用 typescript 代替 JSDoc。为此,您需要导出 ParentState 接口并将 as a type 导入到 Child 组件,如下所示:

    // Parent.tsx
    import * as React from "react";
    import { Child } from "./Child";
    
    export interface ParentState {
      /**
       * Stores the list of errors encountered during render.
       */
      errors: string[];
    }
    
    export class Parent extends React.Component<{}, ParentState> {
      state = {
        errors: [],
      };
    
      render() {
        return <Child errors={this.state.errors} />;
      }
    }
    
    // Child.tsx
    
    import type { ParentState } from "./Parent";
    
    interface ChildProps {
      errors: ParentState["errors"];
    }
    
    export function Child(props: ChildProps) {
      return (
        <ul>
          {props.errors.map((error, index) => (
            <li key={index}>{error}</li>
          ))}
        </ul>
      );
    }
    

    但是,我认为这里更好的解决方案是使用单独的类型并在 Parent 和 Child 中使用它。

    【讨论】:

    • 感谢您找到相关的 TS 问题。这是一个很好的解决方案,但如果将来出现纯 JSDoc 解决方案,我将保留这个问题。顺便说一句:根据我的经验,声明 type ChildProps = Pick&lt;ParentState, 'errors'&gt; 也有效。
    猜你喜欢
    • 1970-01-01
    • 2020-02-21
    • 2015-06-02
    • 1970-01-01
    • 2021-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-05
    相关资源
    最近更新 更多