I get this error when I try to set fontWeight
in TypeScript:
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...'.
Even though 400
is a correct number it could be any number and therefore I get the error as I understand it. I can track this error to React.CSSProperties that specifies that fontWeight
should look like this:
fontWeight?: CSSWideKeyword | "normal" | "bold" | "bolder" | "lighter" | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900;
What I can't do is set test: React.CSSProperties
const styles = (theme: Theme) => ({
test: {
fontWeight: 400
}
});
I can do it like this but it is not how Material UI handles classes.
const test: React.CSSProperties = {
fontWeight: 400
}
Complete code:
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>
);
}
}
Currently accepted answer for this question is just a workaround. The proper way to solve this problem is using createStyles
function from Material-UI.
const styles = (theme: Theme) => createStyles({
test: {
fontWeight: 400
}
});
See the material UI documentation.
Solved it:
const styles = (theme: Theme) => ({
test: {
fontWeight: 400
} as React.CSSProperties
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With