【发布时间】: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