Typescript error when passing a function as a prop that returns SX style

Viewed 36

Let's say I have a parent component that wants to pass down a function to a child reusable component that make changes to the styles of the child component:

const getSxProp: SxProps<Theme> = (theme: Theme) => ({
  mt: 1,
  '.My-CSS-to-overwrite': {
    padding: '12px 16px 8px 16px',
  },
});

export const ParentComponent = () => {

  return <ChildComponent sxProp={getSxProp} />
}

Then in the child, I have something like this:

type ChildComponentProps = {
  sxProp?: (theme: Theme) => SxProps<Theme>;
};

export const ChildComponent = ({ sxProp }: ChildComponentProps) => {
  return (
    <Box
      sx={theme => {
        if (sxProp) {
          return sxProp(theme);
        }

        return null;
      }}>
      <div>Some content</div>
    </Box>
  );
};

Now, this code works and makes changes to my child styles accordingly. However, I get this typescript error:

No overload matches this call.
  Overload 1 of 2, '(props: { component: ElementType<any>; } & SystemProps<Theme> & { children?: ReactNode; component?: ElementType<any>; ref?: Ref<unknown>; sx?: SxProps<...>; } & CommonProps & Omit<...>): Element', gave the following error.
    Type '(theme: Theme) => SxProps<Theme>' is not assignable to type 'SxProps<Theme> | undefined'.
      Type '(theme: Theme) => SxProps<Theme>' is not assignable to type '(theme: Theme) => SystemStyleObject<Theme>'.
        Type 'SxProps<Theme>' is not assignable to type 'SystemStyleObject<Theme>'.
          Type '(theme: Theme) => SystemStyleObject<Theme>' is not assignable to type 'SystemStyleObject<Theme>'.
  Overload 2 of 2, '(props: DefaultComponentProps<BoxTypeMap<{}, "div">>): Element', gave the following error.
    Type '(theme: Theme) => SxProps<Theme>' is not assignable to type 'SxProps<Theme> | undefined'.ts(2769)

It looks like it doesn't like the fact that I pass a callback to the sx prop, then run a function inside it.

Does anyone know how to fix this issue?

1 Answers

I'm not familiar with SxProps however it seems there is a typing error.

You probably meant

type ChildComponentProps = {
  sxProp?: SxProps<Theme>; // instead of (theme: Theme) => SxProps<Theme>
};
Related