简体   繁体   English

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

[英]Generate type definitions from JS React components that use `prop-types`

We have a component like:我们有一个像这样的组件:

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,
   }

   .....

}

Is there some tooling to enable type generation to a typescript declaration file to generate something like:是否有一些工具可以为 typescript 声明文件启用类型生成,以生成如下内容:

interface ITooltip {
    children: React.Node,
    someProp: string
}

Some reference:一些参考:

If you install @types/prop-types you can use the InferProps generic type to generate types like that:如果你安装@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> {}

The type is more verbose due to typings of prop-types , but it gives you the correct result in usage.由于prop-types ,该类型更加冗长,但它为您提供了正确的使用结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM