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
I've 'fixed' this by doing the following module augmentation:
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.
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: