Skip to content

fix(types): cheaper annotated declaration sites, and sound generic polymorphic props - #5794

Merged
quantizor merged 3 commits into
6.xfrom
fix/types-annotated-cost-and-polymorphic-narrowing
Aug 10, 2026
Merged

quantizor merged 3 commits into
6.xfrom
fix/types-annotated-cost-and-polymorphic-narrowing

Conversation

@quantizor

@quantizor quantizor commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Type-only work on the 6.x type surface: two consumer-facing fixes, .attrs type-check speedups, and broadened perf coverage. No runtime change; the consumer type-perf budget and the web + native type-test suites stay green.

1. Explicitly annotated styled components type-check faster

Assigning a styled component to an explicit type, as isolatedDeclarations and any package that emits .d.ts files must (const Button: IStyledComponentBase<'web', ...> = styled.button\`), used to cost several times more to check than an inferred one: the annotation's styleand the component's widenedstylewere two different csstype representations compared property by property. The inlinestylewidening now builds on React's ownCSSProperties, the same type a hand-written annotation carries, so the comparison short-circuits (~21% fewer types created for that pattern on a 40-component fixture), with no change to what style accepts. Adds a declaration-site (annotated`) kind to the type-perf fixture so the axis is guarded.

2. styled() on a generic polymorphic component keeps its props narrow (#5756)

Wrapping a component whose props are generic over an element type (<C extends React.ElementType>(props: PolymorphicProps<C, OwnProps>)) used to let the styled result accept prop values the component itself rejects: styled(Button) would take variant="anything" even though <Button variant="anything"> is a type error. Introspecting such a component resolves props at the React.ElementType constraint, where the bag picks up a [key: string]: any index signature; the style widening's Omit then collapsed the declared narrow props into that index. The widening now leaves an index-signature bag untouched, so the narrow props survive and a bad value is caught in the wrapper too. Valid props, children, and plain targets are unaffected.

3. .attrs() is cheaper to type-check

Two costs on the .attrs path are removed. Object-form .attrs() leaves the rendered target unchanged but still re-resolved that target's whole prop bag on every call, so .attrs on an HTML/SVG tag cost far more than on a wrapped component; it now reuses the props already resolved for the tag. And making attrs-provided keys optional ran an avoidably expensive mapped pass over the target's full prop set; switching that to a distributed built-in Omit cuts it further while keeping a union-props attrs target's member-specific props intact. Net on the consumer fixture: about 4% fewer instantiations and 7.5% fewer types created versus the start of this PR, with every .attrs form (object, function, as-redirect, chained) behaving identically.

Broadened perf coverage (no runtime effect)

The type-perf fixture gained four exotic kinds, each pricing a distinct type-system code path and each doubling as a compile-fail canary: an un-introspectable polymorphic-factory target, a generic polymorphic target (guards fix #2), a function-form .attrs target redirect, and a no-shared-keys union target. Plus style/ref call-site variants and canary pins for the #5756 soundness properties. Each is a changeset-free fixture change; the budget was re-measured.

…olymorphic props

Two independent type fixes, each with its own changeset:

- Rebase the widened inline `style` prop on `React.CSSProperties` so an explicit
  `IStyledComponentBase`/`IStyledComponent` annotation, which isolatedDeclarations
  and `.d.ts`-emitting packages must write, relates against a shared csstype
  instantiation instead of walking csstype per component. About 21% fewer types
  created at annotated declaration sites, with no behavior or call-site change.

- Gate the style widening off for a prop bag carrying a string index signature,
  so `styled()` wrapping a generic polymorphic component keeps its declared props
  narrow instead of collapsing them to `any` under built-in `Omit` (#5756).

Also adds an `annotated` kind to the consumer type-perf fixture so the
declaration-site annotation axis is guarded going forward.
Copilot AI lite review requested due to automatic review settings August 10, 2026 19:37
@changeset-bot

changeset-bot Bot commented Aug 10, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 1cbf893

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
styled-components Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important

Both fixes verify clean — I rebuilt dist, ran the #5756 generic-polymorphic repro (kkwasny-rtbh's exact PolymorphicComponentProps shape) and the repo's GenericPolyButton fixture against the built declarations on TS 5.9.3 / @types/react 18, and confirmed the new @ts-expect-errors are genuine positive controls (removing the gate turns them into unused directives). One consequence of the index gate is real but undersold in what this PR ships: it also disables style custom-property widening for non-any index-signed prop bags, not just [k: string]: any ones. The direction is defensible (the wrapper's style now types exactly like the unwrapped component, and the key-preserving alternative measured expensive), but the "only ... a style that is already any" claim is inaccurate for concrete-typed index bags, and nothing pins the new style behavior on them. See the inline comment on the gate.

Reviewed changes

  • Rebased the widened inline style onto React.CSSProperties — CSSPropertiesWithVars in types.ts now builds on React's own CSSProperties, so a hand-written declaration annotation (IStyledComponentBase<'web', … & { style?: React.CSSProperties }>) relates to the styled result's style by the intersection-member fast path instead of walking csstype member by member. No change to accepted style values (custom props, style={undefined}, bad values all behave as before).
  • Gated style widening off for string-index-signed prop bags — the new string extends keyof P branch in OverrideStyle returns such bags untouched, keeping a generic polymorphic component's narrow props intact after introspection and making styled(Button) reject prop values the component itself rejects (#5756).
  • Added an annotated kind to the type-perf fixture — guards the declaration-site axis (weights moved; budget re-measured in type-perf.budget.json on TS 5.9.3 / @types/react 18, instantiations 850,743 → 936,809), with docs/type-performance.md gaining a "declaration-site relation" section and a 6th load-bearing bullet.
  • Replaced the #5756 BASELINE-PIN in src/test/types.tsx — the pinned "wrapper accepts a prop the direct call rejects" is now a positive control asserting both the direct and wrapped calls reject a bad variant, with a valid call added to prove the new behavior doesn't over-prune.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

Comment thread packages/styled-components/src/types.ts Resolved
…e-perf fixture

- Skip re-resolving the render target's props when object-form `.attrs()` leaves
  the target unchanged (the common case). That path rebuilt the ~265-key
  intrinsic prop bag through `ComponentPropsWithRef` on every `.attrs` call, only
  to reproduce what `OuterProps` already held; the fast path returns it directly.
  About 6.8% fewer consumer type-check instantiations, with no change to the
  resulting component's accepted props. Redirecting the target (`.attrs({ as })`,
  including the function form) is unaffected.

- Add four exotic fixture kinds, each pricing a `types.ts` conditional arm no
  existing kind reached and each doubling as a compile-fail canary:
  `permissiveFactory` (the un-introspectable `WidenUntypedProps` fallback),
  `genericPoly` (the #5756 `string extends keyof P` `OverrideStyle` gate),
  `attrsAsRedirect` (function-form `.attrs` union-target seam), and
  `disjointTarget` (the `keyof B extends never` empty-bag guard). Plus `style` and
  `ref` call-site variants on `plainTag`, and `canary.tsx` pins for the two #5756
  soundness properties. The budget was re-measured; the growth is the fixture, not
  the cost.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ No new issues in this increment — the delta is clean. This review is not an approval solely because the previously-flagged typed-index style contract thread (on the OverrideStyle gate) remains open and untouched by these commits.

Reviewed changes

Incremental since the prior pullfrog review (9031285), per commit 7d2696ec:

  • Added an .attrs target-unchanged fast path — object-form .attrs() leaves the render target as-is, so [PrivateResolvedTarget] extends [Target] returns MergeProps<OuterProps, Props> directly instead of re-merging the ~265-key ComponentPropsWithRef<Target> bag. The bracket keeps a function-form .attrs (resolved target is a union) on the re-merge branch, preserving the TS2589-sensitive seam and the .attrs({ as }) redirect path. I traced the type algebra across the common shapes (fresh tags, wrapped components, chained .attrs, plain-function targets, KnownTarget-typed function-form redirects); the skip is behavior-preserving and only ever avoids re-reproducing what OuterProps already carried.
  • Broadened the type-perf fixture with four exotic kinds — permissiveFactory (Mantine-style un-introspectable target), genericPoly (the #5756 gate), attrsAsRedirect (function-form .attrs union-target seam), disjointTarget (the keyof B extends never guard) — plus style/ref call-site variants on plainTag. Each kind prices a conditional arm no other kind reaches; each doubles as a compile-fail canary. The genericPoly/permissiveFactory kinds correctly cannot catch a gate regression on their own (a valid value still compiles when the gate is dropped), which is why the canary pins (CanaryPolyBad, CanaryFactoryOk) exist and are genuine positive controls — a gate regression turns CanaryPolyBad's @ts-expect-error into an unused directive (TS2578) and fails the clean-compile gate.
  • Re-measured the type-perf budget and updated docs/type-performance.md with the fast-path rationale and the four-kind canary taxonomy. The measured drift (instantiations 936,809 → 926,001; types 34,797 → 42,528; memory +5%) is fixture growth from the exotic kinds on top of the fast-path savings, consistent with how the fixture treats unionTarget/annotated.
  • Added the consumer-facing changeset describing the .attrs type-check speedup; correct wording, no internal names.

No new findings in this delta.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

The largest single cost of `.attrs` on a tag is `MakeAttrsOptional`'s mapped pass
over the ~266-key widened intrinsic bag (~30% of that kind's types), not the
target-redirect seam: a union redirect and a single-concrete redirect price
identically, and collapsing the `ComponentPropsWithRef` re-merge moves ~6 types
while breaking four redirect contracts.

Switch that pass from `FastOmit` to built-in `Omit` distributed through an outer
`P extends unknown`. Built-in `Omit` is the more optimized here (the same result
the `OverrideStyle` note records), and the distribution runs it per union member
so a union-props attrs target (`styled(Pressable).attrs(...)`) keeps its
member-specific keys instead of collapsing to the union's common ones; a bare
undistributed `Omit` drops `href`.

Consumer fixture: -7.5% types, -4.1% instantiations, memory flat. Contract suite
(web + native) and every `.attrs` form (object, function, as-redirect, chained,
union-target) unchanged.
@quantizor
quantizor merged commit 00b9ee2 into 6.x Aug 10, 2026
7 of 8 checks passed
@quantizor
quantizor deleted the fix/types-annotated-cost-and-polymorphic-narrowing branch August 10, 2026 21:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants