Generate type definitions from JS React components that use `prop-types`
Asked Answered
S

1

7

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:

Stria answered 25/11, 2020 at 20:37 Comment(4)
Have you find a solution (to achieve it as part of the build process)?Haygood
@Sagivb.g I did not, and I have moved on from that project.Stria
@Sagivb.g Did you solve it? I encoutered on same problem.Chervonets
@Chervonets Unfortunately noHaygood
W
3

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.

Whitefaced answered 25/11, 2020 at 21:22 Comment(3)
I am hoping there is a way to generate ts declaration files as part of a build process. This is a package which is written in js, that is imported into a ts project.Stria
The TypeScript compiler is doing that for you. With the -d or --declaration you generate a d.ts file with all your exported members.Whitefaced
But will tsc generate d.ts files for props defined only via prop-types in js only React components, that is the workflow I am looking for.Stria

© 2022 - 2024 — McMap. All rights reserved.