Material-ui: Bug with styled types

Created on 12 Feb 2020  ·  5Comments  ·  Source: mui-org/material-ui

  • [x] The issue is present in the latest release.
  • [x] I have searched the issues of this repository and believe that this is not a duplicate.

Steps to Reproduce 🕹

When we use Custom props for styled function when get the error:

interface StyledButtonProps {
  type: string;
}
const StyledButton = styled(
  ({ type, ...other }: StyledButtonProps & ButtonProps) => <Button {...other} />
)({
  color: props => (props.type === "test" ? "red" : "green"),
  display: "block"
});

My sandbox https://codesandbox.io/s/hopeful-tesla-e9fut

| Tech | Version |
| ----------- | ------- |
| Material-UI | v4.9.2 |
| React | 16.12.0 |
| Browser | Chrome 80 |
| TypeScript | 3.7.5 |
| etc. | |

typescript

All 5 comments

Use the generic types of styled like so:

import { DefaultTheme } from '@material-ui/core/styles/defaultTheme';

interface StyledButtonProps {
  type: string;
}
const StyledButton = styled(
  ({ type, ...other }) => <Button {...other} />
)<DefaultTheme, StyledButtonProps & ButtonProps>({
  color: props => (props.type === "test" ? "red" : "green"),
  display: "block"
});

@michelalbers Thanks a lot. Could you please add these examples to the documentation?

@oliviertassinari @mbrookes what the stage for this issue? I think it's a significant case for adding to documentation? or better ts types handling?

Adding @eps1lon who is 100% more skilled in this area than me. (I suspect that this should be ∞, give or take, but I'm not a big proponent of percentages > 100! 😆)

Maybe we should change type of ComponentCreator to something like that?

type ExtractProps<T> = T extends React.ElementType<infer P> ? P : {};

export type ComponentCreator<Component extends React.ElementType> = <
  Theme = DefaultTheme,
  Props extends {} = ExtractProps<Component>
>(

that way styled seems to infer props type as expected and this change feels more or less backward compatible

Was this page helpful?
0 / 5 - 0 ratings

Related issues

iamzhouyi picture iamzhouyi  ·  3Comments

ghost picture ghost  ·  3Comments

mb-copart picture mb-copart  ·  3Comments

ghost picture ghost  ·  3Comments

rbozan picture rbozan  ·  3Comments