I'm refactoring a React application from Javascript to Typescript but I'm having some troubles migrating especially the shape
PropType. My code looks like this right now:
import React from 'react';
import PropTypes from 'prop-types';
interface FooterProps {
labels: FooterLabels;
}
interface FooterLabels {
body: string;
}
const Footer: React.FC<FooterProps> = ({ labels }) => (
<div className="footer">
{/* ... */}
</div>
);
Footer.propTypes = {
labels: PropTypes.shape({
body: PropTypes.string.isRequired
}).isRequired
};
export default Footer;
But I'm getting an error in the PropTypes:
Type 'Validator<InferProps<{ body: Validator<string>; }>>' is not assignable to type 'Validator<FooterLabels>'.
Type 'InferProps<{ body: Validator<string>; }>' is not assignable to type 'FooterLabels'.
Property 'body' is optional in type 'InferProps<{ body: Validator<string>; }>' but required in type 'FooterLabels'.ts(2322)
FooterAppPromo.tsx(5, 3): The expected type comes from property 'labels' which is declared here on type 'WeakValidationMap<FooterProps>'
I'm new to Typescript so sometimes I don't really know what I'm doing, but I tried to do stuff like:
Footer.propTypes = {
labels: PropTypes.shape<FooterLabels>({
body: PropTypes.string.isRequired
}).isRequired
};
But I'm getting the errors. I tried searching for example implementations but I couldn't find any.
EDIT
Typescript types and PropTypes are not the same thing. You can easily write an example where a Typescript validation passes but you still get a PropTypes warning (e.g. an external API that returns a number where should be a string). Here's two articles explaining why:
So my question is how can I make nested PropTypes objects (PropTypes.shape()
or maybe PropTypes.objectOf()
) work with TypeScript?
interface
andReact.FC<FooterProps>
are enough. You don't needpropTypes
on React with Typescript – UvularpropTypes
. Right now,tsc
errors out with:Type 'undefined' is not assignable to type 'MetaType'.
– Perineum