Search code examples
javascriptreactjstypescriptstyled-components

How to type attrs and styles props in styled components - React


Styles:

interface BtnProps {
  variant: string;
  size: string;
  mr: number;
}

const Btn = styled(Button).attrs<BtnProps>(({ variant, size }) => ({
  forwardedAs: Link,
  size: size ?? 'md',
  variant: variant ?? 'primary'
}))<BtnProps>`
  color: white;
  margin-right: ${({ mr }) => mr ?? '10px'};
  &:hover {
    color: white;
  }
`;

TypeScript doesn't check type of mr variable, i can put whatever i want in it.


Solution

  • Issue with my code was forwardedAs.

    Got an answer:

    Yes when you render a custom component instead of a HTML primitive, e.g. "div" we don't filter props.

    source: https://github.com/styled-components/styled-components/issues/3039