gpt4 book ai didi

javascript - typescript JSDoc ...休息类型语法

转载 作者:行者123 更新时间:2023-12-05 04:54:48 26 4
gpt4 key购买 nike

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

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

我的问题是在 React 功能组件中使用的“rest”参数将 props 传递给另一个 React 组件。在下面的示例中,Typescript 将 Prop “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 —— 尽量不要诉诸于此)

最佳答案

我找到了 @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 参数的方括号 - 您可以将该参数标记为可选。

关于javascript - typescript JSDoc ...休息类型语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65604723/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com