Home > OS >  React component prop throwing error typescript
React component prop throwing error typescript

Time:12-02

I'm trying to use a component on which I have defined the prop type like this

export type Props = {
  variant: "green" | "red" | "grey" | "yellow";
};

and the component is like this

const Tag: FC<Props> = (props) => {
  const { variant, ...rest } = props;

  return (
    <div
      {...rest}
      sx={{
        bg: variant,
      }}
    />
  );
};

Now when I try to consume this component like this

const statusColour: { [key: string]: string } = {
  running: "green",
  stopped: "red",
  idle: "grey",
  default: "green"
};

const variant = statusColour[value]
          ? statusColour[value]
          : statusColour["default"];

<Tag variant={variant} />

I get this error on the variant attribute

Type 'string' is not assignable to type '"green" | "red" | "grey" | "yellow"'.ts(2322)

types.d.ts(2, 5): The expected type comes from property 'variant' which is declared here on type 'IntrinsicAttributes & TagProps & { children?: ReactNode; }'

(JSX attribute) variant: "green" | "red" | "grey" | "yellow"

Can somebody help me out on how to resolve it, thanks

CodePudding user response:

Type 'string' is not assignable to type '"green" | "red" | "grey" | "yellow"'.ts(2322)

This error means that any string of type string is not assignable to the union of specific strings "green" | "red" | "grey" | "yellow". This makes sense. "banana" is a string, but it should NOT be assignable to "apple" | "pear".

To fix it you need to tell the type of statusColor that it may only have values that are one of those specific strings.

So just make the values of your mapped type the same as the variant in Props.

const statusColour: { [key: string]: Props['variant'] } = {
  running: "green",
  stopped: "red",
  idle: "grey",
  default: "green"
};

Playground


Or clean it up by making the variant union it's own type alias:

type MyVariant = "green" | "red" | "grey" | "yellow"

export type Props = {
  variant: MyVariant;
};

const statusColour: { [key: string]: MyVariant } = {
  running: "green",
  stopped: "red",
  idle: "grey",
  default: "green"
};

Playground

CodePudding user response:

so figured out my mistake. Basically, the variant prop expected something of type "green" | "red" | "grey" | "yellow"; but I was passing a string. To resolve it, this is what I did:

const statusColour: { [key: string]: string } = {
  running: "green",
  stopped: "red",
  idle: "grey",
  default: "green"
};

const variant = statusColour[value] as "green" | "red" | "grey" | "yellow"
          

<Tag variant={variant} />

I know this is not the best solution. So if somebody could post a better solution, that would be super helpful. Thanks

  • Related