当我尝试在TypeScript中设置fontWeight时收到此错误:

Types of property 'test' are incompatible.
    Type '{ fontWeight: number; }' is not assignable to type 'Partial<CSSProperties>'.
        Types of property 'fontWeight' are incompatible.
            Type 'number' is not assignable to type '"inherit" | 400 | "initial" | "unset" | "normal" | "bold" | "bolder" | "lighter" | 100 | 200 | 30...'.

即使400是正确的数字,它也可以是任何数字,因此,据我了解,我得到了错误。我可以将此错误跟踪到React.CSSProperties,该错误指定fontWeight应该如下所示:
fontWeight?: CSSWideKeyword | "normal" | "bold" | "bolder" | "lighter" | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900;

我不能做的是设置test: React.CSSProperties
const styles = (theme: Theme) => ({
    test: {
        fontWeight: 400
    }
});

我可以这样做,但不是Material UI处理类的方式。
const test: React.CSSProperties = {
    fontWeight: 400
}

完整的代码:
import * as React from "react";
import * as ReactDOM from "react-dom";
import * as ReactRouter from "react-router";
import { withRouter } from "react-router-dom";
import { withStyles } from 'material-ui/styles';
import Badge from 'material-ui/Badge';
import Grid from 'material-ui/Grid';
import { Theme } from 'material-ui/styles';

interface IState {
    userName: string;
}

interface IProps {
    history?: any;
    classes?: any;
}

const styles = (theme: Theme) => ({
    test: {
        fontWeight: 400
    }
});

class Menu extends React.Component<IProps, IState> {
    constructor(props: IProps) {
        super(props);
        this.state = {
            userName: localStorage.userName ? 'userName ' + localStorage.userName : "",
        }
    }
    render() {
        return (
            <div>
                <Grid container spacing={24}>
                    <Grid item xs={12} className={this.props.classes.test}>
                    <span>Test</test>
                    </Grid>
                </Grid>
            </div>
        );
    }
}

最佳答案

解决了:

const styles = (theme: Theme) => ({
    test: {
        fontWeight: 400
    } as React.CSSProperties
});

07-24 14:16