I'm trying to ensure type safety for a specific converting scenario. The goal is to map over the palette
object and convert any entries to key-value pairs, similar to how tailwindcss handles color configurations. However, I am facing an issue where the type of colors
does not include the gray colors, only the non-converted entry keys.
const palette = {
white: 'white',
gray: {
100: '#eeeeee',
200: '#e0e0e0',
300: '#bbbbbb',
},
};
type ColorVariants = keyof typeof palette;
function convertToColors(color: ColorVariants) {
return Object.fromEntries(
Object.entries(palette[color]).map(([key, value]) => [`${color}${key}`, value]),
);
}
/**
result ->
{
"gray100": "#eeeeee",
"gray200": "#e0e0e0",
"gray300": "#bbbbbb",
}
*/
const grays = convertToColors("gray")
The types are incorrect in this context
// Resulting Type
// const colors: {
// white: string;
// }
//
// Expecting Type
// const colors: {
// white: string;
// gray100: string;
// gray200: string;
// gray300: string;
// }
const colors = {
white: palette.white,
...convertToColors("gray")
}