I'm trying to update some of my old Typescript that used material-ui@next to the new @material-ui/core.
Typescript Version: 2.8.3
@material-ui/core: 1.1.0
I've implemented a very simple component that takes a single prop but the typescript compiler throws the following error when it is used
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>'.
Here's the component 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);
i've also encounter some problemes while trying to create a type for my styles, so here how you can properly type your style if WithStyles from material-ui doesn't work
const styles = (props) => ({
container: {
display: 'flex',
}
})
type Props = {
blabla: string;
classes: Record<keyof ReturnType<typeof styles>, string>
}
You may also want to create an utiliy type for this
const styles = (props) => ({
container: {
display: 'flex',
}
})
type MaterialStyle<S> = {
classes: Record<keyof S, string>
}
type Props = {
blabla: string;
} & MaterialStyle<ReturnType<typeof styles>>
Let me know if you find a better and shorter way to do the same thing :)
Add classes
to IPlaceholderProps as a property:
export interface IPlaceholderProps {
...
classes
}
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