reactjs - Uso de withStyles con Typescript en el nuevo @material-ui/core
Estoy intentando actualizar parte de mi antiguo TypeScript que usaba material-ui@next al nuevo @material-ui/core.
Typescript Version: 2.8.3
@material-ui/core: 1.1.0
He implementado un componente muy simple que toma una sola propiedad, pero el compilador de TypeScript lanza el siguiente error cuando se usa
src/App.tsx(21,26): error TS2322: Type '{ classes: true; imageUrl: string; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Placeholder> & Readonly<{ children?: ReactNode; }>...'.
Type '{ classes: true; imageUrl: string; }' is not assignable to type 'Readonly<PROPS_WITH_STYLES>'.
Types of property 'classes' are incompatible.
Type 'true' is not assignable to type 'Record<"root", string>'.
Aquí está el componente Placeholder.tsx
import * as React from "react";
import { StyleRulesCallback, WithStyles, withStyles, StyledComponentProps } from "@material-ui/core";
export interface IPlaceholderProps {
imageUrl: string;
}
export const STYLES: StyleRulesCallback<"root"> = theme => ({
root: {
display: "flex",
justifyContent: "center",
alignItems: "center"
}
});
export type PROPS_WITH_STYLES = IPlaceholderProps & WithStyles<"root">;
export class Placeholder extends React.Component<PROPS_WITH_STYLES, {}> {
render(){
return <div className={this.props.classes.root}>
<img src={this.props.imageUrl}/>
</div>;
}
}
export default withStyles(STYLES, { withTheme: true })<PROPS_WITH_STYLES>(Placeholder);
Respuesta #1
También me he encontrado con algunos problemas al intentar crear un tipo para mis estilos, así que aquí está cómo puedes tipar correctamente tu estilo si WithStyles de material-ui no funciona
const styles = (props) => ({
container: {
display: 'flex',
}
})
type Props = {
blabla: string;
classes: Record<keyof ReturnType<typeof styles>, string>
}
También puede que desee crear un tipo de utilidad para esto
const styles = (props) => ({
container: {
display: 'flex',
}
})
type MaterialStyle<S> = {
classes: Record<keyof S, string>
}
type Props = {
blabla: string;
} & MaterialStyle<ReturnType<typeof styles>>
Hazme saber si encuentras una manera mejor y más corta de hacer lo mismo :)
Respuesta #2
Agrega classes a IPlaceholderProps como una propiedad:
export interface IPlaceholderProps {
...
classes
}
