从使用“prop-types”的 JS React 组件生成类型定义

col*_*r-j 6 javascript typescript reactjs react-proptypes

我们有一个像这样的组件:

import PropTypes from 'prop-types';
import React from 'react';

export default class Tooltip extends React.Component {
  static propTypes = {
    /**
     * Some children components
     */
    children: PropTypes.node.isRequired,
    /**
     * Some property
     */
    someProp: PropTypes.string,
   }

   .....

}
Run Code Online (Sandbox Code Playgroud)

是否有一些工具可以为打字稿声明文件启用类型生成,以生成类似以下内容的内容:

interface ITooltip {
    children: React.Node,
    someProp: string
}
Run Code Online (Sandbox Code Playgroud)

一些参考:

ddp*_*rrt 3

如果安装,@types/prop-types您可以使用InferProps泛型类型来生成如下类型:

import { InferProps } from "prop-types"

type ITooltip = InferProps<typeof Tooltip.propTypes>

// or interfaces if that's what you prefer:
// interface ITooltip extends InferProps<typeof Tooltip.propTypes> {}
Run Code Online (Sandbox Code Playgroud)

由于 的输入,该类型更加冗长prop-types,但它会为您提供正确的使用结果。

  • 但是,“tsc”是否会为仅通过“js”React 组件中的“prop-types”定义的 props 生成“d.ts”文件,这就是我正在寻找的工作流程。 (2认同)