When attempting to set the fontWeight
property in TypeScript, I encounter the following error:
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...'.
Although using 400
is a valid number, the error occurs because it could be any number based on my understanding. This can be traced back to React.CSSProperties which defines the acceptable values for fontWeight
, like so:
fontWeight?: CSSWideKeyword | "normal" | "bold" | "bolder" | "lighter" | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900;
The issue arises when trying to set test: React.CSSProperties
const styles = (theme: Theme) => ({
test: {
fontWeight: 400
}
});
An alternative approach would be as follows, although it deviates from how Material UI manages classes:
const test: React.CSSProperties = {
fontWeight: 400
}
Total code snippet is presented below:
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>
);
}
}