Home > database >  How to type Mui v5 Chip color prop with value as object key
How to type Mui v5 Chip color prop with value as object key

Time:11-24

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: Edit wild-cloud-6q050i

  • Related