3

I'm updating my project to MUI version 5. It is recommended to use emotion CSS. I want to use the theme property. Now typescript is asking for type for theme. The version below does not work. How can I provide a type?

import { Theme } from "@mui/material"

const Root = styled('div')(({ theme: Theme }) => ({
  background: theme.palette.grey[50],
}))
NearHuscarl
  • 66,950
  • 18
  • 261
  • 230
vuvu
  • 4,886
  • 12
  • 50
  • 73

1 Answers1

7

If you happen to import the styled API from @mui/styles, then it wouldn't work because it's not provided with a MUI theme out-of-the-box. You need to createTheme and pass it to the ThemeProvider yourself, then augment the type of DefaultTheme because by default it's an empty interface:

import { Theme } from '@mui/material/styles';

declare module '@mui/styles' {
  interface DefaultTheme extends Theme {}
}

But be aware that it's not recommended to use the legacy package @mui/styles. See more detail on my other answer.


In case you've already imported styled from @mui/material/styles: Since you're using typescript, remove the Theme type, the styled function can infer the type of the property theme in the callback, so you don't have to do anything:

const Root = styled('div')(({ theme }) => ({
  background: theme.palette.grey[50],
}))

But theoretically, if the theme is untyped, this is how you add it:

const Root = styled('div')(({ theme }: { theme: Theme }) => ({
  background: theme.palette.grey[50],
}))
NearHuscarl
  • 66,950
  • 18
  • 261
  • 230