Home > OS >  Typescript doesn't work with JS module PropTypes
Typescript doesn't work with JS module PropTypes

Time:01-27

I have React module written in plain JS. I don't want rewrite entire module into typescript, so I use just propTypes. E.g.

const Alert = ({
    className = "",
    alert = ""
}) => (
    <div className={`alert ${className}`}>
        {alert}
    </div>
)

Alert.propTypes = {
    className: PropTypes.string,
    alert: PropTypes.string
}

I publish it into npm registry.

Now my new typescript project use this module. So I import that component and expect, that typescript will whisper props and find some error during compilation.

<Alert className="neutral" noExistProp={true} />

I expect that typescript catch noExistProp, but it's not happening, so I probably misunderstood this concept. Is there some way how comunicate Proptypes with typescript?

CodePudding user response:

TypeScript has its own way of defining prop types for components, and it does not automatically recognize propTypes defined in plain JavaScript.

If you don't want to use any additional libraries and want to use propTypes and TypeScript together in your project, you can define an interface for your props, and then use it in your component and pass it as a type to the propTypes.

In your case, you could define an interface for your props like this:

interface AlertProps {
    className?: string;
    alert?: string;
}

and then in your component:

const Alert: React.FC<AlertProps> = ({
    className = "",
    alert = ""
}) => (
    <div className={`alert ${className}`}>
        {alert}
    </div>
)

CodePudding user response:

InferProps provided by prop-types may be helpful, assuming the propTypes are still available after your module has been compiled.

I know you don't wish to modify the existing module but perhaps you can look into writing a .d.ts declaration file in your new project/module for typing up the module's components without rewriting it entirely. Perhaps you could even use InferProps in the declaration. This is the approach most use for supporting typescript with vanillaJS libraries and it's not so bad depending on how many exports you have.

Other than that I'm not sure what option you have I'm afraid.

  • Related