styled-components / styled-components

Visual primitives for the component age. Use the best bits of ES6 and CSS to style your apps without stress 💅
https://styled-components.com
MIT License
40.11k stars 2.48k forks source link

Add types for props from .attrs and "as" #4291

Open bjornsnoen opened 1 month ago

bjornsnoen commented 1 month ago

Fixes:

Noticed that someone else opened PR #4288 yesterday, I will assume that their fix for attrs is more correct than mine but I'll leave this until that PR is merged or other wise addressed.

carloslibardo commented 3 weeks ago

I use your branch locally to test the .attrs issue in my project, but the https://github.com/styled-components/styled-components/issues/4076 issue still happening to me:

export const Calendar = styled(Icon).attrs({
  type: 'TypeA',
  color: 'ColorA',
  size: 20,
})`
  margin: 12px 15px 12px 24px;
`;

<Calendar /> returning error

Type '{}' is missing the following properties from type 'FastOmit<FastOmit<Substitute<IconProps, IconProps>, never>, never>': type, color

<Calendar color='ColorA' type='TypeA'/> works well

@edit

My Icon component:

import Config from '@config/index';
import React from 'react';
import { ViewStyle, StyleProp } from 'react-native';

export type IconProps = {
  /** The default size value is 16px */
  size?: 8 | 12 | 14 | 16 | 20 | 22 | 24 | 28 | 36 | 40 | 48 | 64 | 128;
  type: 'TypeA' | 'TypeB'
  color: 'ColorA' | 'ColorB';
  style?: StyleProp<ViewStyle>;
};

const Icon = ({ size = 16, type, color, style }: IconProps) => {
  const RenderedIcon = Config.NEW_ICONS[type];

  return (
    <RenderedIcon
      width={size}
      height={size}
      style={style}
      color={getIconColor(color)}
    />
  );
};

export { Icon };

My Icon is a SVG.

It happens with my other component which is styled.text too.

export const PressBackAgainText = styled(Typography).attrs({
  color: 'WHITE',
})``;

What I find strange is that when instantiating the component with styled components, the .attrs is not correctly reading the component's typing, even if I determine that it is mandatory, autocomplete only shows it as optional, and does not report an error in the time to instantiate.

bjornsnoen commented 3 weeks ago

@carloslibardo could you format your comment properly using github code markdown and give the definition for the Icon component and I can take a look?

carloslibardo commented 3 weeks ago

@bjornsnoen i updated the comment with more infos

quantizor commented 1 week ago

I ended up taking the other PR, can you check to see if your issue is resolved with current main branch?

joealden commented 2 days ago

Even if #4288 solves the .attrs problem, would we not still want the changes related to as? Maybe worth splitting out into it's own PR if possible?