javascript - TypeScript 2.4.1 -> fontWeight -> Tipo 'number' no se puede asignar al tipo '"inherit"' | 400 |
Obtengo este error cuando intento establecer fontWeight en 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...'.
Aunque 400 es un número correcto, podría ser cualquier número y, por lo tanto, obtengo el error según lo entiendo. Puedo rastrear este error a React.CSSProperties que especifica que fontWeight debería verse así:
fontWeight?: CSSWideKeyword | "normal" | "bold" | "bolder" | "lighter" | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900;
Lo que no puedo hacer es establecer test: React.CSSProperties
const styles = (theme: Theme) => ({
test: {
fontWeight: 400
}
});
Puedo hacerlo así, pero no es como Material UI maneja las clases.
const test: React.CSSProperties = {
fontWeight: 400
}
Código completo:
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>
);
}
}
Respuesta #1
Lo resolví:
const styles = (theme: Theme) => ({
test: {
fontWeight: 400
} as React.CSSProperties
});
Respuesta #2
La respuesta actualmente aceptada para esta pregunta es solo una solución temporal. La forma correcta de resolver este problema es usando la función createStyles de Material-UI.
const styles = (theme: Theme) => createStyles({
test: {
fontWeight: 400
}
});
Consulta la documentación de Material UI.
