Reputation: 1562
I'm doing my first steps with Typescript-React-styledComponents,
and I'm trying this simple case where I'm passing a size
prop via a parent component, which will set the font-size of the child component.
EDITED:
ts throws me this:
Property 'size' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<Component<ThemedOuterStyledProps<DetailedHTMLProps...'.
I noticed size
might be a problematic prop name, cuz I don't get any error on the other props. do you know why?
more general question - what am I missing?
Parent Component
<Parent>
<Child text="Red Bikini" color='red' size={2}/>
</Parent>
Child Component
import * as React from 'react';
import styled from 'styled-components';
//EDITED
interface headerSizeType {
1: string;
2: string;
3: string;
4: string;
5: string;
6: string;
}
const size: headerSizeType = {
1: '2em',
2: '1.5em',
3: '1.17em',
4: '1em',
5: '.83em',
6: '.67em'
}
interface ChildProps {
text: string;
size?: number;
color?: string;
style?: any;
children?: React.ReactChildren;
className?: string;
}
const ChildStyle = styled.h2`
display: inline-block;
color: ${(props: any) => props.color || 'black'};
font-size: ${props => size[props.size] || 'black'}; //1st Error here
`;
const Child= (props: ChildProps): JSX.Element => {
console.log(props.color)
return (
<ChildStyle color={props.color} size={props.size}> //2nd Error here
{ props.text }
</ChildStyle>
);
};
export default Title;
Upvotes: 0
Views: 1686
Reputation: 2069
You should specify prop types for your styled component like so:
type MyStyledProps = {
color?: string;
size?: string;
}
const ChildStyle = styled.h2<StyledComponent<'h2', any, MyStyledProps, never>>`
display: inline-block;
color: ${(props) => props.color || 'black'};
font-size: ${props => size[props.size] || 'black'};
`;
Then your errors should go away.
Upvotes: 1
Reputation: 1562
I found the solution, though I didnt master understanding the issue :)
but I temporarly fixed it by casting the styled-component as any, like so:
const ChildStyle = styled.h2`
display: inline-block;
color: ${(props: any): string => props.color || 'black'};
font-size: ${(props:any): any => headerSizes[props.size] || 'black'};
` as any;
I know casting any types arent good practice, and that's why it's a temporary solution.
I heard there's a Theme Object within styled-component, that gives you a more nice and clean solution for this.
EDITED:
another solution for types of styled-components types:
https://github.com/jacob-ebey/styled-components-ts
Upvotes: 1