Issue
How can I type MUI Chip prop color
if actual value comes from an object? At the moment I use any
but it is not a good option. And one more question, is as keyof typeof CHIP_COLORS
correct way for typing?
import { Chip, Stack } from "@mui/material";
const DATA = [
{
id: 2,
status: "success"
},
{
id: 3,
status: "finished"
},
{
id: 4,
status: "error"
}
];
const CHIP_COLORS = {
finished: "primary",
error: "error",
success: "success"
};
export default function App() {
return (
<Stack
sx={{gap: 5}}
>
{DATA.map(({ id, status }) => {
return (
<Chip
color={CHIP_COLORS[status as keyof typeof CHIP_COLORS] as any}
/>
);
})}
</Stack>
);
}
Codesandbox: https://codesandbox.io/s/festive-breeze-s4vpfk?file=/src/App.tsx
Solution
you can create custom types.
type eventType = "finished" | "success" | "error";
type colorType = "primary" | "error" | "success" | "default" | "secondary" | "info" | "warning" | undefined
your data type:
const DATA:{ id:number, status:eventType }[] = [
{
id: 2,
status: "success"
},
...
chip color type:
const CHIP_COLORS: { [key in eventType]: colorType } = {
finished: "primary",
error: "error",
success: "success"
};
component:
{DATA.map(({ id, status }) => {
return (
<>
<Chip color={CHIP_COLORS[status]} />
</>
);
})}
Answered By - Okan Karadag
Answer Checked By - - Marie Seifert (ReactFix Admin)