How to use PropTypes.shape with Typescript How to use PropTypes.shape with Typescript typescript typescript

How to use PropTypes.shape with Typescript


The PropTypes error is because you are trying to use a PropType.shape, the shape allows you to have optional values on your shape, and in this case, your interface is strict, which means you do not have any kind of optional value, and React.Validator is trying to infer your types behind with your interfaces and that makes the error appear.

In simple words, if you have a strict interface with non-optional values, instead of using PropType.shape you should use PropType.exact and that should prevent the error.

E.G:

Footer.propTypes = {  labels: PropTypes.exact({    body: PropTypes.string  }).isRequired};

For that reason on your error message appears

Property 'body' is optional in type 'InferProps<{ body: Validator; }>' but required in type 'FooterLabels'.ts(2322)

EDITED

This happens only because you are using on the componentconst Footer: React.FC<FooterProps> = ({ labels }) => (

The FC ( FunctionComponent Interface ) looking into the interfaces is presented as

interface FunctionComponent<P = {}> {        (props: PropsWithChildren<P>, context?: any): ReactElement<any, any> | null;        propTypes?: WeakValidationMap<P>;        contextTypes?: ValidationMap<any>;        defaultProps?: Partial<P>;        displayName?: string;    }

The line that we should highlight here is the propTypes?: WeakValidationMap<P>; This is the one that infers our types based on our PropTypes.

You have a second option to use types on React, but I do not recommend it, instead of using FC, you can use ReactNode type, but you will lose the inferences that you have on the FC interface type inferring.

E.G.function Footer = ({ labels }:FooterProps): ReactNode => (


Actually you don't need propTypes here - labels got just one nested field body that is typeof FooterLabels.

interface FooterProps {  labels: {     body: FooterLabels;  };}


interface FooterProps {  labels: PropTypes.InferProps<{ body: string }>}