1

I am trying to build a react application in typescript, and having some trouble typing the component correctly.

This is my code:

import React from 'react';
import PropTypes, { InferProps } from 'prop-types';
import clsx from 'clsx';
import { makeStyles } from '@material-ui/styles';
import { Typography, Link, Theme } from '@material-ui/core';

const useStyles = makeStyles((theme: Theme) => ({
    root: {
        padding: theme.spacing(4),
    },
})); 

const Footer: any = (props: InferProps<typeof Footer.propTypes>): JSX.Element => {
    const { className, ...rest } = props;
    const classes = useStyles();

    return (
        <div {...rest} className={clsx(classes.root, className)}>
        </div>
    );
};

Footer.propTypes = {
    className: PropTypes.string,
};

export default Footer;

The problem is that, if I use InferProps (from the prop-types library), I am unable to use const Footer: React.FC but instead have to use any.

Little side question: Am I doing this the right way here?

Kind regards

3
  • have you tried const Footer: React.FC<InferProps<typeof Footer.propTypes>>? Commented Jan 13, 2020 at 8:29
  • why don't you define your own interface instead of using PropTypes? Commented Jan 13, 2020 at 8:30
  • prop-types were already present (I am redesigning my app), plus prop-types work at runtime whereas interface only at compile time, so I have to make both. This way, I only have to create 1. Commented Jan 13, 2020 at 8:32

1 Answer 1

6

Since you're using TypeScript you might not need to use prop-types anymore because:

  • TypeScript would do all the job during the compiling and won't let you build unmatched types
  • PropsTypes are very heavy lib and you get of it in production anyways (only dev wich is coveded by TS)

With that being said I suggest you to use the following code:

import React from 'react';
import clsx from 'clsx';
import { makeStyles } from '@material-ui/styles';
import { Theme } from '@material-ui/core';

const useStyles = makeStyles((theme: Theme) => ({
  root: {
    padding: theme.spacing(4),
  },
}));

interface OwnProps {
  className: string;
}

const Footer: React.FC<OwnProps> = (props) => {
  const { className, ...rest } = props;
  const classes = useStyles();

  return <div {...rest} className={clsx(classes.root, className)} />;
};

export default Footer;
Sign up to request clarification or add additional context in comments.

1 Comment

Ok so not a real answer to the question but I am going for your solution! The internet agrees with you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.