Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using withStyles with Typescript in the new @material-ui/core

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);
like image 761
BlisterFingers Avatar asked May 28 '18 03:05

BlisterFingers


2 Answers

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 :)

like image 120
Daniel Gabor Avatar answered Oct 03 '22 03:10

Daniel Gabor


Add classes to IPlaceholderProps as a property:

export interface IPlaceholderProps {
    ...
    classes
}
like image 24
Aniko Litvanyi Avatar answered Oct 03 '22 04:10

Aniko Litvanyi