0

I am using React and TypeScript in my app. How do I get rid of below error?

import { styled } from "linaria/react";

type Color = {
  color: "default" | "red" | "green" | "blue";
};


const handleColorType = ({ color }: Color) => {
  switch (color) {
    case "default":
      return "#03a9f3";
    case "red":
      return "#f56342";
    case "green":
      return "#f56342";
    case "blue":
      return "#f56342";
    default:
      return "#fff";
  }
};

export const Title = styled.h1`
  font-size: 50px;
  display: inline-flex;
  margin: 150px auto 0;
  color: ${({ color }) => handleColorType({ color // <---- here I get the error })};
`;

Then I get this Typescript error:

(property) color: "default" | "red" | "green" | "blue" Type 'string | undefined' is not assignable to type '"default" | "red" | "green" | "blue"'. Type 'undefined' is not assignable to type '"default" | "red" | "green" | "blue"'.ts(2322) color.ts(2, 3): The expected type comes from property 'color' which is declared here on type 'Color'

meez
  • 3,783
  • 5
  • 37
  • 91
  • A type definion like `type Color = "default" | "red" | "green" | "blue"` means it has only 4 valid values...Any other value apart from these 4 is not allowed. – Nalin Ranjan Mar 02 '22 at 09:15
  • The problem is not with the function, but at the call-site. Do you have any variable named "color" which you are then using to construct `{ color }` object at the call-site? – Nalin Ranjan Mar 02 '22 at 09:47
  • Like.. `handleColorType({ color // <---- here I get the error })`, what is the type of `color` here?? – Nalin Ranjan Mar 02 '22 at 09:48
  • With a generic like `export const Title = styled.h1` it's working. But why? – meez Mar 02 '22 at 10:18

1 Answers1

0

Try to define type of prop as Color in styled component aswell

 color: ${({ color }: Color) => handleColorType({ color })};

because now its just optional string

Wraithy
  • 1,722
  • 1
  • 5
  • 13
  • not that's not working. Here I have to return a string as color – meez Mar 02 '22 at 09:10
  • 2
    Sorry, try to declare props type of Styled component: `export const Title = styled.h1` according to [documentation](https://styled-components.com/docs/api#using-custom-props) – Wraithy Mar 02 '22 at 09:56