简体   繁体   中英

React Typescript Function Component typing

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM