chen
chen

Reputation: 4490

How to declare this existing variable's type when playing Typescript system in React?

I am playing Typescript with React lately, and after copy&paste this example code that works under ES6 to my .tsx file, my Typescript environment tells me the following error " Parameter 'theme' implicitly has an 'any' type." and my browser refuse to render.

import * as React from 'react';
import { withStyles } from '@material-ui/core/styles';
import Paper from '@material-ui/core/Paper';
import Typography from '@material-ui/core/Typography';

const styles = theme => ({
  root: theme.mixins.gutters({
    paddingTop: 16,
    paddingBottom: 16,
    marginTop: theme.spacing.unit * 3,
  }),
});

function PaperSheet(props) {
  const { classes } = props;
  return (
    <div>
      <Paper className={classes.root} elevation={4}>
        <Typography variant="headline" component="h3">
          This is a sheet of paper.
        </Typography>
        <Typography component="p">
          Paper can be used to build surface or other elements for your application.
        </Typography>
      </Paper>
    </div>
  );
}


export default withStyles(styles)(PaperSheet);

How can I fix it? What type theme should I declare?

Upvotes: 0

Views: 625

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249686

If you use the option noImplicitAny or strict you need to specify types where the compiler can't infer them (this is a good thing). In this case theme should be of type Theme and you should also provide a type for props:

import * as React from 'react';
import { withStyles, Theme } from '@material-ui/core/styles';
import Paper from '@material-ui/core/Paper';
import Typography from '@material-ui/core/Typography';

const styles = (theme : Theme) => ({
  root: theme.mixins.gutters({
    paddingTop: 16,
    paddingBottom: 16,
    marginTop: theme.spacing.unit * 3,
  }),
});

function PaperSheet(props : { classes: { root: string } }) {
  const { classes } = props;
  return (
    <div>
      <Paper className={classes.root} elevation={4}>
        <Typography variant="headline" component="h3">
          This is a sheet of paper.
        </Typography>
        <Typography component="p">
          Paper can be used to build surface or other elements for your application.
        </Typography>
      </Paper>
    </div>
  );
}

export default withStyles(styles)(PaperSheet);

Upvotes: 3

Related Questions