Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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

Some reference:

  • https://github.com/salesforce/design-system-react/issues/1346
  • https://github.com/Microsoft/dts-gen
  • https://github.com/KnisterPeter/react-to-typescript-definitions
like image 281
coler-j Avatar asked Aug 12 '26 13:08

coler-j


1 Answers

If you install @types/prop-types you can use the InferProps generic type to generate types like that:

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.

like image 83
ddprrt Avatar answered Aug 14 '26 10:08

ddprrt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!