Skip to content

perf(types): cut the consumer type-check cost and fix two live type bugs - #5790

Merged
quantizor merged 5 commits into
mainfrom
perf/consumer-type-cost
Aug 6, 2026
Merged

quantizor merged 5 commits into
mainfrom
perf/consumer-type-cost

Conversation

@quantizor

Copy link
Copy Markdown
Contributor

What changes for consumers

Type-checking a project that uses styled-components got substantially cheaper. v7 had regressed well past published 6.5.0 on every metric a consumer pays for; this closes the gap and lands slightly ahead of 6.5.0.

Two type bugs that are live today are also fixed:

  • Disjoint union props are no longer eaten. styled.div<{ onlyA: string } | { onlyB: number }> rejected both props. keyof over a union yields only the keys common to every member, so the empty-prop-bag fast path swallowed the whole union.
  • Un-introspectable targets no longer reject every prop. Wrapping a polymorphic factory component (Mantine's, for one) rejected everything including children. Fixes styled(MantineButton) rejects all props in 6.4.2 (regression from 6.1.x) #5756.

Plus: a declared style prop now merges with the target's own instead of replacing it, and React Native gets real style typing.

Why it regressed, and what stops it recurring

The cause was found by measurement, not inspection. OverrideStyle applied a built-in Omit to the merged prop bag, and since TypeScript does not normalize X & (A | B) into a union, keyof saw only the shared keys and member-specific props vanished. Target props now resolve once per target rather than once per JSX call site.

Nothing in the repo could have caught this, and docs/typescript-performance.md was quoting a figure that nothing checked. So this PR also adds the harness that makes the claim falsifiable:

  • scripts/typePerf.mjs type-checks a generated fixture against the built .d.ts the way a consumer resolves it, and gates instantiations, types, and memory against type-perf.budget.json.
  • It runs in CI after the build, with no continue-on-error.
  • The fixture carries a union-target case with a member-specific call site, so the distribution that keeps A | B intact has a measurable cost. Without it, a future pass would read "free to remove" off a fixture that never exercised it.
  • A @ts-expect-error canary guards the skipLibCheck fake win: a dist that cannot resolve its own dependencies degrades every export to any, still compiles, and would otherwise report an enormous improvement.
  • The hard-coded figures are gone from the docs. The budget file is the live number.

Notes for review

  • src/test/types.tsx pairs every accepted prop with a rejected one. Without the negative controls, widening props to an index signature would accept everything and pass the whole section while the union was in fact gone.
  • The Mantine block asserts its own premise, so the test fails loudly if the fixture ever becomes introspectable and stops testing what it claims to.
  • src/test/types.native.tsx is new, and pins the runtime gate that keeps web CSS out of native.
  • One documented exception: .attrs() target resolution deliberately stays on ComponentPropsWithRef. A function-form .attrs makes the target a union, and distributing inside that distribution measured catastrophically worse.
  • The all-optional union case ({ a?: 1 } | { b?: 2 }) still takes the fast path. That limitation is pinned as an explicit @ts-expect-error rather than left undiscovered.

Consumer type-check cost was 6.2x what the previous major costs, and
nothing in CI could see it: test:types measures the library's own
workload over src, where a regression in the public prop-resolution
types barely registers.

Add a consumer budget that type-checks a generated fixture against the
built dist/*.d.ts, then fix what it measured. Against the same fixture,
TypeScript 5.9.3 and @types/react 19.2.14:

  types           199,982 -> 30,980   (6.5.0 published: 32,270)
  instantiations  1,910,667 -> 734,385
  memory          711 MB -> 187 MB

The bulk is TargetProps: the shape it replaces applies
ComponentPropsWithRef per JSX call site against a ~150-member
constraint, rebuilding a large prop bag each time. Tags now resolve by
indexed access, which already carries ref via DetailedHTMLProps.

Three correctness fixes fall out of the same work, all live before it:

- Moving the style widening to once per target rather than per call
  site. Post-merge the type is X & (A | B), which TypeScript does not
  normalize to a union, so a distributive conditional does not
  distribute and built-in Omit sees only the union's shared keys. A
  component typed ButtonProps | AnchorProps stopped accepting href.
- Discriminating the empty-prop-bag fast path with `{} extends B`.
  keyof a union is the keys common to every member, so a union of
  disjoint shapes reports never while being a real prop bag, and the
  fast path dropped it wholesale.
- Deciding permissiveness from the target rather than the finished prop
  bag, so an un-introspectable target stays permissive even when the
  component declares transient props of its own.

MergeProps additionally keeps a declared style type constraining the
fields it names while the target's remaining CSS still comes through,
and the widening is gated on the runtime so web CSS stops reaching the
native entry.

The fixture carries a union-typed target on purpose. Without one the
distribution that keeps A | B intact prices as free, which is how it
came to be removed; because the run fails on any fixture compile error,
the gate now also refuses to compile against a package with that bug.
useInjectedStyle was a use-prefixed function that called no hooks,
invoked from two arms of the render-cache branch. Nothing was wrong at
runtime, but the name is the trap: it makes a conditional call to a
non-hook read as a legitimate hook call, which is how a hook ends up
inside that branch in the first place.

Add the regression test that was missing when the conditional
useDebugValue was fixed. It records the hook sequence by wrapping
React's own use* exports, so a hook added to the render path later is
covered without the test being told about it, and asserts the sequence
rather than a count, since swapping two hooks keeps the count identical
and still breaks React's ordering rule.

StrictMode is the instrument because it is the only way the cache-hit
path is reachable through the public API: React.memo blocks an ordinary
re-render with equal props before it reaches the component, and any
re-render memo lets through fails the same shallow comparison the cache
uses. Under StrictMode the render body runs twice and refs survive
between passes, so pass 2 finds the cache populated. Verified by
measurement: a StrictMode mount runs two render passes and exactly one
interpolation.

Also correct the changeset for the original fix. It claimed the bug
could crash components; React 19.2.3's useDebugValue allocates no hook
slot, and the "Rendered fewer hooks than expected" throw is guarded
solely by currentHook.next, which useDebugValue never advances. The
observable effect was a debug value missing from React DevTools.
- `Substitute` was still imported in constructWithOptions after every use
  site moved to `MergeProps`.
- `Substituted` and `Merged` are referenced only inside types.ts. They
  stay named so hovers print a name instead of the expansion, which
  needs no export; the dts rollup still emits them as plain declarations
  so `Substitute` and `MergeProps` resolve.
- The tolerance band had two homes: the constant in the script and a
  copy in the budget file, with the check reading the copy and --update
  writing the constant, so a hand-widened band was silently reset. The
  band is policy and lives with its reasoning in the script; the budget
  file records only what was measured. The per-metric presence check is
  unaffected, since a missing `measured` entry is what yields NaN bounds.
- typePerf header advertised a bare `--count 500`, which is refused
  rather than compared. Documented the pairing with --against/--update.
- The `chained` fixture comment named cursor 8; the kinds ahead of it
  sum to 13. Restated as the invariant that actually matters, since the
  number goes stale on any weight edit.
- A canary directive's stated reason read as though the case involved
  `as`, which it does not.
Dead weight and instruments that could not fail the way they claimed.

Instruments:

- The staleness check ignored only `src/test`, but suites also live in
  `src/models/test`, `src/utils/test` and beside the code as `*.test.*`.
  Editing any of them made `type-perf` refuse to run with "dist is older
  than src", which is exactly the cry-wolf the ignore list exists to
  prevent. Now keyed on whether a path reaches dist at all.
- The three metrics were spelled out in four places: the parse, the
  tolerance table, the completeness check and the comparison. A metric
  present in some and missing from others yields NaN bounds, every
  comparison against NaN is false, and the run reports "within budget"
  while checking nothing. That is the failure the budget-file check
  already guards against, reproduced one level up in the script's own
  tables. One METRICS table now drives all four.
- The fixture's kind switch reached generic wrappers through `default:`,
  so a kind added to KIND_WEIGHTS and not to the switch would have
  priced the wrong shape silently. It throws now.
- The hook-sequence test fell back to the whole recorded sequence when
  the segment boundary was absent. Two symmetric halves would still
  compare equal, so the test would pass while measuring something else.
  The boundary is asserted instead.

Tests for behavior that had none. Each verified to fail with its seam
ablated:

- The erased `IStyledComponent<'web'>` surface is widened by a different
  seam than the one in `constructWithOptions`, and nothing exercised it,
  so the whole seam could be deleted with the suite still green.
- Function-form `.attrs()` on an un-introspectable target reads the
  target's props off the callback argument; only the object form was
  covered.
- The widening also fires for targets that are introspectable and simply
  declare no props (`React.FC`, `() => ReactElement`). No discriminator
  separates them from a polymorphic factory, both being `{}`, so it is
  characterized rather than fixed.
- `exactOptionalPropertyTypes`: the `& {}` filter is called load-bearing
  in three places and was asserted nowhere.

Corrections. The canary explanation had the TS2578 mechanic backwards
(the expressions error while types are intact, which is what keeps the
directives used). A hover example named `Substituted` where the ordinary
path now prints `Merged`. `WidenForUntypedTarget` claimed every call site
passes target props, which `IStyledComponentBase` does not and cannot.
The `OuterProps` comment named a default that only the function, not the
interface, declares. Plus a dead `React` import in styled.tsx and a dead
`View` import in types.native.tsx, neither caught by anything.
Copilot AI lite review requested due to automatic review settings August 6, 2026 23:15
@changeset-bot

changeset-bot Bot commented Aug 6, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 72d82bb

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 Minor

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.

Pull request overview

Reduces the consumer-facing TypeScript cost of styled-components v7 by restructuring how target props are resolved (once per target, not per JSX call site), while fixing multiple live typing regressions (union prop loss, un-introspectable targets rejecting all props) and adding CI enforcement to prevent future type-perf regressions.

Changes:

  • Refactors core type composition (TargetProps, MergeProps, WidenForUntypedTarget, CustomStyle) to preserve unions, correctly handle un-introspectable targets, and merge declared style with target style (plus native-style correctness).
  • Adds a consumer type-check performance harness (type-perf) with a committed budget and CI gating against the built dist/*.d.ts.
  • Extends type-contract coverage (new native type surface file) and adds a render-cache/hook-sequence regression test.

Reviewed changes

Copilot reviewed 23 out of 24 changed files in this pull request and generated no comments.

Show a summary per file
File Description
packages/styled-components/type-perf.budget.json Records the baseline budget for consumer type-check diagnostics.
packages/styled-components/src/types.ts Core type changes: target prop resolution, union preservation, style merging/widening, new CustomStyle.
packages/styled-components/src/test/types.tsx Adds type-level regression coverage for union props, un-introspectable targets, and declared-style merging.
packages/styled-components/src/test/types.native.tsx New compile-only suite pinning native entry typing (especially style behavior).
packages/styled-components/src/test/memoization.test.tsx Adds a rules-of-hooks regression test validating cache hit/miss paths keep hook order identical.
packages/styled-components/src/native/index.ts Switches native entry’s prop extraction to TargetProps<'native', ...> to avoid web-only style widening.
packages/styled-components/src/models/StyledComponent.ts Removes a helper wrapper and ensures useDebugValue is outside the render-cache branch.
packages/styled-components/src/index.ts Exports CustomStyle from the public surface.
packages/styled-components/src/constructors/styled.tsx Uses TargetProps for web constructor typing instead of per-call-site ComponentPropsWithRef.
packages/styled-components/src/constructors/constructWithOptions.ts Replaces Substitute with MergeProps and applies widening based on the target’s introspectability.
packages/styled-components/scripts/typePerf.mjs New consumer type-perf fixture generator + budget enforcer running against built dist.
packages/styled-components/package.json Adds type-perf script entry.
knip.jsonc Marks the new native type test file as an entry so knip doesn’t flag it as unused.
docs/typescript-performance.md Updates documentation to describe the new budgeted consumer-cost harness and the new type strategy.
AGENTS.md Documents the render-cache hook-order invariant and the new type-perf command.
.gitignore Ignores the generated .type-perf fixture directory.
.github/workflows/test.yml Adds pnpm --filter styled-components type-perf to CI after build.
.changeset/untyped-target-props.md Changeset for fixing un-introspectable targets rejecting all props.
.changeset/union-props-survive-styled.md Changeset for union-props preservation through styled() and as.
.changeset/native-style-typing.md Changeset for native style typing correctness and preventing web-only widening on native.
.changeset/hooks-cache-hit-debug-value.md Changeset describing consistent debug value behavior across renders.
.changeset/disjoint-union-props.md Changeset for disjoint-union prop loss fix (and documented limitation for all-optional unions).
.changeset/declared-style-merges.md Changeset for merging declared style with target style and introducing CustomStyle.
.changeset/consumer-type-check-cost.md Changeset announcing consumer type-check cost reduction and CI budgeting.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@quantizor
quantizor merged commit ef8178b into main Aug 6, 2026
6 checks passed
@quantizor
quantizor deleted the perf/consumer-type-cost branch August 6, 2026 23:36
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.

styled(MantineButton) rejects all props in 6.4.2 (regression from 6.1.x)

2 participants