【问题标题】:Typescript JSDoc ...Rest type syntaxTypescript JSDoc ...Rest 类型语法
【发布时间】:2021-04-12 17:28:15
【问题描述】:

在现有的大型 react/redux 应用程序上使用 typescript 开始时遇到问题。

作为概念证明,我已将我的一个 react 文件转换为 .ts 文件。我正在尝试将使用 JSDoc 的类型添加到导入的 JS 文件中,以告诉 Typescript 哪些参数可用(而不是仅将模块声明为 .d.ts 文件中的任何参数)。

我的问题在于反应功能组件中使用的“rest”参数,以将道具传递给另一个反应组件。在下面的示例中,Typescript 将道具“id”标识为不存在。

.tsx 文件:

import ReactFunction from 'wherever_it_is/react_function';

//inside another react component
<ReactFunction
    prop1="something"
    id="unique"
/>

wherever_it_is/react_function.jsx 文件:

/**
 * @typedef {object} ReactFunctionProps
 * @prop {boolean} prop1 - descriptive text
 * @prop {...any} ...otherProps - pass through props
 */

/**
 * descriptive comment about ReactFunction
 *
 * @param {ReactFunctionProps} props
 * @return {import("@types/react").JSX.Element}
 */
export default function ReactFunction({
    prop1,
    ...otherProps
}) {
    return (
        <OtherThing
            {...otherProps}
        />
    );
}

使用 Typescript 4.1.3。

任何人都知道 Typescript JSDoc 的正确语法是“...rest”运算符吗?据我所知,我使用的是 https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html 中提到的其余运算符的正确语法。

还有其他建议吗? (除了declare module wherever_it_is/react_function; 之外,我知道它会将模块导入为any - 尽量不要诉诸于此)

【问题讨论】:

  • 是否有理由从 JSDoc 开始而不是添加 Typescript 类型?如果你真的想要的话,你可以刚刚开始添加 JSDoc 和一些 JS 工具。
  • 除了将 Typescript 添加到现有项目并摸索自己的方式之外,没有其他理由。我想我发现了一份越来越严格的使用 Typescript 的方法列表,并且使用 JSDoc 比创建实际的 Typescript 类型更高。似乎更适合创建 Typescript 类型,而不是学习所有专门的 JSDoc 语法以及 Typescript。
  • JSDoc 非常适合使用 Typescript 附加文档以对函数或参数提供更多描述,但由于它是完全独立的,因此一旦添加更详细的类型信息,类型的语法将完全不同且冗余直接在 Typescript 中。

标签: javascript reactjs typescript jsdoc


【解决方案1】:

一种解决方法是创建一个 .d.ts 文件并在 Typescript 语法中定义类型。

wherever_it_is/react_function.d.ts:

export default function ReactFunction({
    prop1,
    ...otherProps 
}: {
    [x: string]: any;
    prop1: any;
}): JSX.Element;

虽然这在技术上不能回答问题,但它是一种前进的方式。我的怀疑是 JSDoc 类型方法不支持 ...rest 用例。

【讨论】:

    【解决方案2】:

    我找到了@typedef 方式,您可以在其中构造新的 Props 类型,然后将其与 React.HTMLAttributes 相交,就像在纯 Typescript 语法中一样:

    /**
     * @typedef {Object} TextInputProps
     * @property {string} [className]
     * @property {string} label
     */
    
    /**
     * @param {TextInputProps & React.InputHTMLAttributes<HTMLInputElement>} props
     */
    function TextInput({
        className = '',
        label = '',
        ...props
    }) {...}
    

    这种方式似乎有点奇怪,因为您需要将 Typescript 类型和功能与 JSdoc 语法混合,但它对我有用。

    您还可以看到 classname 参数的方括号 - 您可以将该参数标记为可选。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-18
      • 2021-12-21
      • 2020-02-07
      • 1970-01-01
      • 2018-12-22
      • 1970-01-01
      • 2018-01-11
      • 2019-02-09
      相关资源
      最近更新 更多