8

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);
1

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

Add classes to IPlaceholderProps as a property:

export interface IPlaceholderProps {
    ...
    classes
}

1 Comment

That does make it compile, thanks. Kinda feel like withStyles isn't worth all this boilerplate, though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.