Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

sx prop as a function for type safety #26631

Closed
1 task done
Raicuparta opened this issue Jun 7, 2021 · 2 comments
Closed
1 task done

sx prop as a function for type safety #26631

Raicuparta opened this issue Jun 7, 2021 · 2 comments
Labels
package: system Specific to @mui/system typescript

Comments

@Raicuparta
Copy link

The new sx prop has the advantage of being able to refer to theme keys without having to import a theme object, which is great. Problem is, using theme keys as plain strings wastes the benefit of type safety in TypeScript. As far as I'm aware, it wouldn't be feasible to type check the possible values via typed template strings.

  • I have searched the issues of this repository and believe that this is not a duplicate.

Summary 💡

Accept functions in the sx prop, with the only argument being the theme.

Examples 🌈

<Box sx={({ palette }) => ({
  backgroundColor: palette.background.paper
})} />

Motivation 🔦

Type safety, while avoiding using the theme hooks in the parent component.

@Raicuparta Raicuparta added the status: waiting for maintainer These issues haven't been looked at yet by a maintainer label Jun 7, 2021
@mnajdova mnajdova added package: system Specific to @mui/system typescript and removed status: waiting for maintainer These issues haven't been looked at yet by a maintainer labels Jun 7, 2021
@mnajdova
Copy link
Member

mnajdova commented Jun 7, 2021

Thanks for the report. We could investigate using template literal types. There is a similar discussion to it in #26475. Regarding the callback, you could use

<Box sx={{
  backgroundColor: ({ palette }) => palette.background.paper
}} />

But I wouldn't recommend changing every prop to callback, only for type safety. I remember we discussed making the sx prop also a function on the theme, but at that moment it felt like there are too many different APIs around it.

@Raicuparta
Copy link
Author

Oh, I wasn't aware that was possible. Closing this then. I did mention template literal types, but honestly it doesn't seem like it's feasible. I'll pay attention to the discussion.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
package: system Specific to @mui/system typescript
Projects
None yet
Development

No branches or pull requests

2 participants