Skip to content

Commit f692ec2

Browse files
authored
fix(types): permissive props for un-introspectable targets, plus as-target autocomplete while typing (#5758)
* fix(types): keep styled() and .attrs() permissive for un-introspectable targets Wrapping a component whose props can't be statically read -- most notably Mantine v7's polymorphic-factory components (Button, Card, Menu.Item), whose generic callable signature defeats React.ComponentPropsWithRef and collapses to {} -- made the resulting styled component reject every prop, including children, at the JSX call site and via .attrs(). Detect the un-introspectable case and widen to a permissive prop bag for it alone; targets with readable prop types keep full checking. The widening is confined to the JSX call surface, never the statics or defaultProps, so the real Props can't leak past the call site. The "no known keys" test is distributed over the prop type first so a bare union of disjoint shapes (keyof intersects to never despite being introspectable) isn't widened by mistake. Closes #5756 * fix(types): collapse polymorphic overloads to one signature so as-target completion survives mid-typing A partially-typed or unknown attribute on a polymorphic styled component (e.g. <Comp as="video" foo l|>) matched none of the call overloads, so overload resolution failed and JSX attribute completion dropped to nothing -- the as-target's props (video's loop/controls/...) disappeared while typing. Replacing the overload set with a single conditional call signature keeps completion resolved at all times. The branching (PolymorphicCallProps) preserves prior behavior: a real as-target substitutes its props; no-as / wrapped-as (Url-typed) keeps Substitute-free base props for ref inference on spread (#5687), wrapped-as assignability (#5734), and plain completion (#5741); forwardedAs substitutes the forwarded target. The single signature instantiates a conditional per JSX usage where the overload set resolved plain usage to a free non-generic overload, so some extra type work is inherent. Two changes keep it small: the target test uses string | AnyComponent rather than the literal-heavy WebTarget (same set, ~6% fewer instantiations across call sites), and the no-target result is a shared alias so it instantiates once. Net vs the prior overloads: instantiations 1,608,782 -> 1,696,358 (+5.4%), check time 2.94s -> 3.22s.
1 parent f9f6546 commit f692ec2

5 files changed

Lines changed: 202 additions & 36 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"styled-components": patch
3+
---
4+
5+
Fix a TypeScript error when wrapping a component whose props can't be statically read, such as Mantine v7's polymorphic-factory components (`Button`, `Card`, `Menu.Item`, and similar). These styled components no longer reject every prop, including `children`; arbitrary props are accepted again at the JSX call site and via `.attrs()`, while components with readable prop types stay fully type-checked.
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'styled-components': patch
3+
---
4+
5+
Keep TypeScript attribute autocomplete working while you type props on a polymorphic styled component. When a component renders a different element through `as` (for example `as="video"`), beginning to type a new prop name could make the whole suggestion list vanish; the rendered element's props now keep autocompleting as you go.

‎packages/styled-components/src/constructors/constructWithOptions.ts‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import {
1212
StyledTarget,
1313
Styles,
1414
Substitute,
15+
WidenUntypedProps,
1516
} from '../types';
1617
import { EMPTY_OBJECT } from '../utils/empties';
1718
import styledError from '../utils/error';
@@ -63,7 +64,12 @@ export interface Styled<
6364
attrs: <
6465
Props extends object = BaseObject,
6566
PrivateMergedProps extends object = Substitute<OuterProps, Props>,
66-
PrivateAttrsArg extends Attrs<PrivateMergedProps> = Attrs<PrivateMergedProps>,
67+
// Widen when the merged props are un-introspectable ({}) so attrs can backfill
68+
// arbitrary keys on e.g. Mantine polymorphic-factory targets, matching the
69+
// permissive JSX call site. Targets with known props are unaffected.
70+
PrivateAttrsArg extends Attrs<WidenUntypedProps<PrivateMergedProps>> = Attrs<
71+
WidenUntypedProps<PrivateMergedProps>
72+
>,
6773
PrivateResolvedTarget extends StyledTarget<R> = AttrsTarget<R, PrivateAttrsArg, Target>,
6874
>(
6975
attrs: PrivateAttrsArg
@@ -129,7 +135,9 @@ export default function constructWithOptions<
129135
templateFunction.attrs = <
130136
Props extends object = BaseObject,
131137
PrivateMergedProps extends object = Substitute<OuterProps, Props>,
132-
PrivateAttrsArg extends Attrs<PrivateMergedProps> = Attrs<PrivateMergedProps>,
138+
PrivateAttrsArg extends Attrs<WidenUntypedProps<PrivateMergedProps>> = Attrs<
139+
WidenUntypedProps<PrivateMergedProps>
140+
>,
133141
PrivateResolvedTarget extends StyledTarget<R> = AttrsTarget<R, PrivateAttrsArg, Target>,
134142
>(
135143
attrs: PrivateAttrsArg

‎packages/styled-components/src/test/types.tsx‎

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -815,3 +815,103 @@ const ToggleWithAttrs = styled(ToggleBase).attrs({ isOpen: false })``;
815815
<ToggleWithAttrs />;
816816
// @ts-expect-error isOpen is boolean, not string
817817
<ToggleWithAttrs isOpen="yes" onToggle={() => {}} />;
818+
819+
/**
820+
* Wrapping a component whose props can't be statically introspected -- e.g.
821+
* Mantine v7's polymorphic-factory components, whose generic callable signature
822+
* makes `React.ComponentPropsWithRef` resolve to `{}` -- must stay permissive at
823+
* the JSX call site rather than reject every prop including `children` (#5756).
824+
*
825+
* The synthetic factory below mirrors Mantine's exact shape: a generic callable
826+
* intersected with `FunctionComponent` statics. Verified against real
827+
* `@mantine/core@7` that this collapses `ComponentPropsWithRef` to `{}`.
828+
*/
829+
type FactoryExtendedProps<Props = {}, OverrideProps = {}> = OverrideProps &
830+
Omit<Props, keyof OverrideProps>;
831+
type FactoryElementType = keyof React.JSX.IntrinsicElements | React.JSXElementConstructor<any>;
832+
type FactoryPropsOf<C extends FactoryElementType> = React.JSX.LibraryManagedAttributes<
833+
C,
834+
React.ComponentProps<C>
835+
>;
836+
type FactoryComponentProp<C> = { component?: C };
837+
type FactoryInheritedProps<C extends FactoryElementType, Props = {}> = FactoryExtendedProps<
838+
FactoryPropsOf<C>,
839+
Props
840+
>;
841+
type PolymorphicFactoryProps<C, Props = {}> = C extends React.ElementType
842+
? FactoryInheritedProps<C, Props & FactoryComponentProp<C>> & {
843+
ref?: any;
844+
renderRoot?: (props: any) => any;
845+
}
846+
: Props & { component: React.ElementType; renderRoot?: (props: Record<string, any>) => any };
847+
848+
interface PolyButtonProps {
849+
variant?: string;
850+
color?: string;
851+
children?: React.ReactNode;
852+
}
853+
type PolymorphicFactoryButton = (<C = 'button'>(
854+
props: PolymorphicFactoryProps<C, PolyButtonProps>
855+
) => React.ReactElement) &
856+
Omit<React.FunctionComponent<PolymorphicFactoryProps<any, PolyButtonProps>>, never> & {
857+
extend: (p: any) => any;
858+
};
859+
declare const PolyButton: PolymorphicFactoryButton;
860+
861+
// The premise: this resolves to `{}` (no statically-known keys).
862+
type PolyButtonResolvedProps = React.ComponentPropsWithRef<typeof PolyButton>;
863+
const _polyPremise: keyof PolyButtonResolvedProps extends never ? true : false = true;
864+
865+
const StyledPolyButton = styled(PolyButton)`
866+
color: red;
867+
`;
868+
// Arbitrary props + children accepted (permissive fallback).
869+
<StyledPolyButton variant="filled" color="blue">
870+
hi
871+
</StyledPolyButton>;
872+
<StyledPolyButton>just children</StyledPolyButton>;
873+
// `as` is still accepted. The fallback can't resolve the `as`-target's own props
874+
// though: a permissive prop bag is required to accept the unknown base props, and
875+
// that same bag types every key (including the target's) as the catch-all, so e.g.
876+
// `href` below is not anchor-checked. This is the unavoidable cost of having no
877+
// base type to substitute against -- an introspectable base keeps full `as` typing.
878+
<StyledPolyButton as="a" href="/x">
879+
link
880+
</StyledPolyButton>;
881+
882+
// `.attrs()` is permissive too for un-introspectable targets, so arbitrary keys
883+
// can be backfilled (matching the JSX call site).
884+
const PolyButtonWithAttrs = styled(PolyButton).attrs({ variant: 'filled', type: 'button' })``;
885+
<PolyButtonWithAttrs color="blue">hi</PolyButtonWithAttrs>;
886+
// Function-form attrs can read arbitrary props (typed `unknown`).
887+
styled(PolyButton).attrs(props => ({ 'data-variant': String(props.variant ?? '') }))``;
888+
// Introspectable targets keep strict `.attrs()` typing.
889+
declare const TypedAttrsComp: (props: { a: string }) => React.ReactElement;
890+
// @ts-expect-error -- `nope` is not a prop of the wrapped component
891+
styled(TypedAttrsComp).attrs({ nope: 1 })``;
892+
893+
// A bare union of disjoint shapes is introspectable, even though `keyof` of the
894+
// union is `never`. It must stay strict, not fall into the permissive branch.
895+
type DisjointUnionProps = { a: string } | { b: string };
896+
declare const DisjointUnionComp: (props: DisjointUnionProps) => React.ReactElement;
897+
const StyledDisjointUnion = styled(DisjointUnionComp)`
898+
color: red;
899+
`;
900+
<StyledDisjointUnion a="x" />;
901+
<StyledDisjointUnion b="y" />;
902+
// @ts-expect-error -- `nonsense` is on neither union member; widening must not fire
903+
<StyledDisjointUnion a="x" nonsense="y" />;
904+
905+
// All-optional props have a non-`never` `keyof`, so they stay strict (the widen
906+
// fallback fires only when there are genuinely no known keys).
907+
declare const AllOptionalComp: (props: { a?: string }) => React.ReactElement;
908+
const StyledAllOptional = styled(AllOptionalComp)``;
909+
// @ts-expect-error -- unknown prop still rejected
910+
<StyledAllOptional nonsense="y" />;
911+
912+
// A union with one empty member (`{} | { a }`) is still introspectable: not every
913+
// constituent is empty, so the distributed check must not widen it.
914+
declare const OneEmptyMemberComp: (props: {} | { a: string }) => React.ReactElement;
915+
const StyledOneEmpty = styled(OneEmptyMemberComp)``;
916+
// @ts-expect-error -- nonsense is on neither member
917+
<StyledOneEmpty nonsense="y" />;

‎packages/styled-components/src/types.ts‎

Lines changed: 82 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -185,7 +185,7 @@ export interface IStyledStatics<
185185
export type PolymorphicComponentProps<
186186
R extends Runtime,
187187
BaseProps extends BaseObject,
188-
AsTarget extends StyledTarget<R> | void,
188+
AsTarget extends StyledTarget<R> | (BaseProps extends { as?: infer A } ? A : never) | void,
189189
ForwardedAsTarget extends StyledTarget<R> | void,
190190
// props extracted from "as"
191191
AsTargetProps extends BaseObject = AsTarget extends KnownTarget
@@ -212,6 +212,47 @@ export type PolymorphicComponentProps<
212212
}
213213
>;
214214

215+
/**
216+
* Resolves the call-site props for one usage of a polymorphic component,
217+
* branching on the supplied `as` / `forwardedAs` targets into the three prior
218+
* overload shapes:
219+
* - `as` is a real render target (e.g. `as="video"`, `as={Component}`):
220+
* substitute that target's props and require `as`.
221+
* - no `as`, or `as` is the wrapped component's own non-target type (e.g.
222+
* Next.js Link's `as?: Url`): Substitute-free base props so ref callbacks
223+
* infer with spread props (#5687), the wrapped `as` type stays assignable and
224+
* optional (#5734), and BaseProps keys keep completing for plain usage (#5741).
225+
* - `forwardedAs` only: substitute the forwarded target's props.
226+
*
227+
* Extracted to a named alias so identical (R, BaseProps, AsTarget,
228+
* ForwardedAsTarget) tuples dedupe across the many JSX call sites in an app.
229+
*
230+
* The target test is `string | AnyComponent`, not the broader `WebTarget`
231+
* (`KnownTarget | (string & {})`): both describe the same set (any string or
232+
* component), but comparing against the ~156 literal members of `KnownTarget`
233+
* here costs ~6% more type instantiations across all call sites. Don't narrow it
234+
* to bare `KnownTarget` -- that drops custom element strings (`as="my-element"`)
235+
* out of the target branch and makes them error.
236+
*/
237+
type PolymorphicCallProps<
238+
R extends Runtime,
239+
BaseProps extends BaseObject,
240+
AsTarget extends StyledTarget<R> | (BaseProps extends { as?: infer A } ? A : never) | void,
241+
ForwardedAsTarget extends StyledTarget<R> | void,
242+
> = [AsTarget] extends [string | AnyComponent]
243+
? PolymorphicComponentProps<R, BaseProps, AsTarget, ForwardedAsTarget> & { as: AsTarget }
244+
: [ForwardedAsTarget] extends [void]
245+
? OverrideStyle<
246+
NoInfer<FastOmit<BaseProps, keyof ExecutionProps>> &
247+
FastOmit<ExecutionProps, 'as' | 'forwardedAs'> & {
248+
as?: BaseProps extends { as?: infer A } ? A : void;
249+
forwardedAs?: BaseProps extends { forwardedAs?: infer A } ? A : void;
250+
}
251+
>
252+
: PolymorphicComponentProps<R, BaseProps, void, ForwardedAsTarget> & {
253+
forwardedAs: ForwardedAsTarget;
254+
};
255+
215256
/**
216257
* This type forms the signature for a forwardRef-enabled component
217258
* that accepts the "as" prop to dynamically change the underlying
@@ -233,46 +274,53 @@ export interface PolymorphicComponent<
233274
forwardedAs?: StyledTarget<R> | undefined;
234275
}
235276
> {
236-
// Default overload (no `as`/`forwardedAs`) is listed first so TypeScript's JSX
237-
// completion resolves to it for plain `<StyledComponent ... />` usage. The
238-
// generic overloads below introduce unsolved type parameters that, when
239-
// visited first, suppress JSX attribute name completions for keys carried by
240-
// `BaseProps` (#5741). Avoids `Substitute` so ref callbacks get contextual
241-
// typing even with spread props (#5687).
242-
//
243-
// `as` / `forwardedAs` here widen to also accept the wrapped component's own
244-
// `as` / `forwardedAs` type when present (e.g. Next.js Link's `as?: Url`), so
245-
// spreading the wrapped component's props onto the styled component remains
246-
// assignable (#5734).
247-
(
248-
props: OverrideStyle<
249-
NoInfer<FastOmit<BaseProps, keyof ExecutionProps>> &
250-
FastOmit<ExecutionProps, 'as' | 'forwardedAs'> & {
251-
as?: BaseProps extends { as?: infer A } ? A : void;
252-
forwardedAs?: BaseProps extends { forwardedAs?: infer A } ? A : void;
253-
}
254-
>
255-
): React.JSX.Element;
256-
257-
// Overload for `as` polymorphism. `as` is required here to prevent TS from
258-
// falling back to the constraint type (`StyledTarget<R>`) which is too wide.
259-
<AsTarget extends StyledTarget<R>, ForwardedAsTarget extends StyledTarget<R> | void = void>(
260-
props: PolymorphicComponentProps<R, BaseProps, AsTarget, ForwardedAsTarget> & { as: AsTarget }
261-
): React.JSX.Element;
262-
263-
// Overload for `forwardedAs` polymorphism (without `as`).
264-
<ForwardedAsTarget extends StyledTarget<R>>(
265-
props: PolymorphicComponentProps<R, BaseProps, void, ForwardedAsTarget> & {
266-
forwardedAs: ForwardedAsTarget;
267-
}
277+
// A single call signature (not several overloads) so JSX attribute completion
278+
// never collapses while an attribute is mid-typed. With multiple overloads, a
279+
// partially-typed or unknown attribute matches none of them, overload
280+
// resolution fails, and completion drops to nothing; one signature always
281+
// resolves, so the rendered target's props keep autocompleting. The branching
282+
// that preserves the prior overload shapes lives in `PolymorphicCallProps`.
283+
<
284+
AsTarget extends StyledTarget<R> | (BaseProps extends { as?: infer A } ? A : never) | void =
285+
void,
286+
ForwardedAsTarget extends StyledTarget<R> | void = void,
287+
>(
288+
props: PolymorphicCallProps<R, BaseProps, AsTarget, ForwardedAsTarget>
268289
): React.JSX.Element;
269290
}
270291

292+
/**
293+
* Some wrapped targets can't be statically introspected and their props
294+
* collapse to `{}` -- most notably polymorphic-factory components (e.g. Mantine
295+
* v7's `Button`, `Card`, `Menu.Item`), whose generic callable signature defeats
296+
* `React.ComponentPropsWithRef`. A closed `{}` would reject every prop at the JSX
297+
* call site, including `children`. Falling back to a permissive prop bag keeps
298+
* these components usable; targets with introspectable props are unchanged.
299+
*
300+
* Applied only to the JSX call surface (`PolymorphicComponent`), never to the
301+
* statics (`IStyledStatics`, `defaultProps`), so internal code keeps the real
302+
* `Props` and the widening can't leak past the call site.
303+
*
304+
* The "no known keys" test is distributed over `Props` first. `keyof` on a union
305+
* intersects each member's keys, so a bare union of disjoint shapes (e.g.
306+
* `{ a: string } | { b: string }`) has `keyof` of `never` despite being fully
307+
* introspectable. Checking each constituent independently widens only when every
308+
* member is truly empty.
309+
*/
310+
export type WidenUntypedProps<Props extends BaseObject> = (
311+
Props extends unknown ? (keyof Props extends never ? true : false) : never
312+
) extends true
313+
? Props & { [key: string]: unknown }
314+
: Props;
315+
271316
export interface IStyledComponentBase<
272317
out R extends Runtime,
273318
in out Props extends BaseObject = BaseObject,
274319
>
275-
extends PolymorphicComponent<R, Props>, IStyledStatics<R, Props>, StyledComponentBrand {
320+
extends
321+
PolymorphicComponent<R, WidenUntypedProps<Props>>,
322+
IStyledStatics<R, Props>,
323+
StyledComponentBrand {
276324
defaultProps?: (ExecutionProps & Partial<Props>) | undefined;
277325
toString: () => string;
278326
}

0 commit comments

Comments
 (0)