I'm currently working on a React project that uses emotion (the styled package) for the css styling and typescript (created with create-react-app). I'm relatively new to typescript and I've hit a bit of a brick wall trying to use props with the same name as an attribute available on the base element I'm trying to style.
For instance, when trying to style a div, if I build an interface that defines a color prop that is an object, I get an error when passing this interface into the styled function. I believe it's complaining because color being an object doesn't satisfy the constraint of color being a string or undefined, which is being set somewhere else (presumably within the typings of the emotion styled function?). Here's a basic example of what I'm trying to do.
import styled from '@emotion/styled';
import { ComponentType } from 'react';
interface ColorPalette {
blue: string;
red: string;
}
interface BoxProps {
color: ColorPalette;
notColor?: ColorPalette;
}
const Box = styled('div')<BoxProps>(({ color, notColor }) => ({ // Here <BoxProps> shows the error that ColorPalette doesn't satisfy the constraint of string
color: color.blue,
backgroundColor: color.red,
}));
const Test: ComponentType = () => <Box color={{ red: 'red', blue: 'blue' }} />; // This doesn't actually show any errors because it recognises that the inputted object matched ColorPalette
export default Box;
Essentially the error I get back is: "Type 'BoxProps' does not satisfy the constraint 'Pick, HTMLDivElement>, "color">, "color">'. Types of property 'color' are incompatible. Type '{ blue: string; red: string } | undefined' is not assignable to type 'string | undefined'. Type '{ blue: string; red:string }' is not assignable to type 'string'."
This is a pretty simple example, in reality I'm using the styled-system library as well, which creates a color prop that has the possibility of being an array or object ( to set different values based on breakpoints), which it then converts to being a string, but the error is the same. It has the same issue on other types of elements, like providing a width prop on an svg element.
I feel like I'm just missing something really basic, that I'm not understanding about Typescript about how I could fix this. I can set the color prop to any in the interface, but then that essentially loses the value of the typings in the first place.
答案 0 :(得分:0)
在您添加了更多详细信息之后,现在我了解到您正在使用styled-components
。您要为styled.div
个道具添加类型。
您可以这样做。
const Box = styled('div')<BoxProps>`
color: ${props => props.color.blue};
backgroundColor: ${props => props.color.red},
`;