skip to Main Content

I have a specific palette set for my material ui theme, which i define as so:

createTheme({
  palette: {
    primary: {
      main: '#193C7D',
      dark: '#112853',
      light: '#2C4DBC',

      '900': '#112853',
      '600': '#16356F',
      '500': '#193C7D',
      '400': '#2C4DBC',
      '100': '#F0F6FF',
    },

I access these values, as well as the system colours, even though there’s no guarantee of them being there. They ARE on the object, I can log out the theme, and even though its typed as dark light main, the values ARE there.

So even though our createTheme lets us specify an entire range of hues, and MUI stores these, they don’t appear accessible through typescript? Then what are those options there for?

The end result, is, i have a full range of hues for all my colors i wish to do this:

const c = styled(Component)(({ theme, color = 'primary' }) => ({
  color: theme.palette[color][600]
})

However, my type system complains that 800 does not exist on type PaletteColor. Should colours on the palette not by PaletteColor & ColorPartial, just like the input for the theme creation? In short, why does the config let you set all these hues if they aren’t used (to my knowledge)?

2

Answers


  1. Chosen as BEST ANSWER

    I've 'fixed' this by doing the following module augmentation:

    declare module '@mui/material/styles' {
      // eslint-disable-next-line @typescript-eslint/no-empty-interface
      interface PaletteColor extends ColorPartial {}
    

    This puts our 0->900 hues on the object, representing the state of my theme truly. Though I am unsatisfied with this as I'm still not sure why material aren't doing this for us. I feel like I'm committing a code smell.


  2. For your specific use case, you can explicitly type the color parameter in your styled component to address the TypeScript error. Here’s how you can do it:

    import { styled } from '@mui/material/styles';
    import { Component } from 'your-component-path'; // Replace with your actual component path
    
    const StyledComponent = styled(Component)(({ theme, color = 'primary' }: { theme: Theme; color?: keyof Theme['palette'] }) => ({
    color: theme.palette[color][600], // Replace 600 with the shade you want to use
    }));
    
    export default StyledComponent;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search