在React中播放Typescript系统时如何声明此现有变量的类型?

时间:2018-06-22 07:43:17

标签: reactjs typescript

我最近正在用React播放Typescript,然后将在ES6下可运行的example code复制并粘贴到我的.tsx文件中,我的Typescript环境告诉我以下错误" Parameter 'theme' implicitly has an 'any' type.",并且我的浏览器拒绝渲染。

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);

我该如何解决?我应该声明什么类型的theme

1 个答案:

答案 0 :(得分:3)

如果使用选项noImplicitAnystrict,则需要指定编译器无法推断它们的类型(这是一件好事)。在这种情况下,theme的类型应该为Theme,并且您还应该为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);