What is TS type for MUI Input styled component?

Viewed 31

team!

Could you, please, give me a hand with this one?

So Mui documentation suggests setting a type for a Mui Styled component as follows:

const MyComponent = styled(MuiComponent)(({ theme }) => ({ // styling })) as typeof MuiComponent

That worked perfectly fine for Box, Container, Button and other components, however, once I did that with I got an error, stating that the type is wrong somehow:

Conversion of type 'StyledComponent<InputProps & { theme?: Theme | undefined; }, {}. {}>' to type '((props: InputProps) => Element) & {muiName: string; }' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. Property 'muiName' is missing in type 'StyledComponent<InputProps & { theme?: Theme | undefined; }, {}. {}>' but required in type '{ muiName: string;}'

I tried using as typeof TextField and React.HTMLProps<HTMLInputElement> thinking that that should work , but nope, TextField gives the same error, and HTMLProps starts complaining about onChange, for some reason.

I've spent some time trying to find a way to resolve it on my own, but it's starting to consume too much time, for such a trivial task, hence I decided to seek assistance amongst those with more experience in TS than me.

Thanks in advance <3

1 Answers

I've tried and both snippets below worked for me:

const MyComponent = styled(Input)(({ theme }) => ({})) as typeof Input
const MyComponent2 = styled(TextField)(({ theme }) => ({})) as typeof TextField

I'm using

"@mui/material": "^5.8.0",
"@mui/styles": "^5.9.2",

It would be better if you could provide more code though.

The solution to your problem is actually described in the error. Typescript wants you to convert it to unknown first like so:

const MyComponent = (styled(Input)(({ theme }) => ({})) as unknown) as typeof Input

However, this is more of a hack to get things working, not the actual solution to your problem.

Related