'Why does sx prop typecheck fail?

I'm trying to use sx prop-based styling in a React app.°

I'd like to access the theme via a so-called theme getter.

When I try using this approach I can see the styles render OK in the browser. However TypeScript complains and I'm finding it challenging to understand the type ancestry and work out what it's saying.

Working sandbox

Not working sandbox

demo of problem

Full error:

No overload matches this call.
  Overload 2 of 2, '(props: DefaultComponentProps<BoxTypeMap<{}, "div">>): Element', gave the following error.
    Type 'string' is not assignable to type 'SystemStyleObject<Theme>'.
  Overload 2 of 2, '(props: DefaultComponentProps<BoxTypeMap<{}, "div">>): Element', gave the following error.
    Type '(theme: any) => { border: string; }' is not assignable to type 'SystemStyleObject<Theme>'.
      Type '(theme: any) => { border: string; }' is not assignable to type 'CSSSelectorObject<Theme>'.ts(2769)
app.tsx(8, 22): Did you mean to call this expression?

Possibly relevant GH discussion 1, 2

Presumably I should by explicitly setting SystemStyleObject, but not sure where to import it from. Any pointers would be appreciated.

° The app uses TypeScript 4.4.1-rc + MUI 5.0.0-beta.4



Solution 1:[1]

This works for me:

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

const style: SxProps<Theme> = {
  position: 'absolute',
  top: '50%',
  left: '50%',
  transform: 'translate(-50%, -50%)',
  width: '100%',
  maxWidth: 900,
  bgcolor: 'background.paper',
  border: '1px solid #a7a7a7',
  boxShadow: 24,
  p: 4,
}

...

<Box sx={style}>

Solution 2:[2]

The way it's typed. Theming function can only be applied to a CSS style and not a class. You can move it down to the border like so:

  <Box
    sx={{
      border: "1px solid red",
      ".some-child": {
        border: (theme) => {
          return "1px solid green";
        }
      }
    }}
  >

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 cau
Solution 2 Daniel Duong