Repository navigation
Commit dfe4baf
authored
feat(types): derive target props once per target, and merge a declared style type (#5784)
* fix(types): derive target props once per target, not per call site
The style widening moves from the merged prop bag at every JSX call site
into TargetProps, where a render target's prop interface is derived. A
target's props are shared by every component built on it, so the Omit
resolves once per tag instead of once per component.
On a 500-component fixture measured against the built declarations,
check time drops by about 40% and types by about 80% relative to the
previous commit. Against 6.4.4 that is roughly 4.5x faster and about a
third of the memory, and it now runs ahead of 6.4.2 on types,
instantiations and check time alike.
Four details are load-bearing, each found by measurement:
- The style test is `'style' extends keyof P`, not
`P extends { style?: infer S }`. The latter is vacuously satisfied by
`{}`, which would give un-introspectable targets a style key and defeat
WidenUntypedProps (#5756).
- Attrs no longer re-applies the widening. Its Props already carry it,
and re-applying stopped Attrs<any> relating to Attrs<OuterProps>.
- The explicit `| undefined` keeps style={undefined} assignable under
exactOptionalPropertyTypes.
- Substitute's second parameter is now unbounded. Bounding it to
BaseObject forces callers to write `TargetProps<T> & BaseObject`, and
`{}` is retained rather than reduced inside an intersection, so the
bound propagates an unreducible node through every downstream prop
bag, costing roughly +160% types and +70% check time on its own.
Because the widening now runs before user props are substituted in, a
`style` type declared on the component replaces it rather than being
unioned with it, and prop extraction reports the widening it previously
hid. Both are pinned by new contract tests.
* test(types): assert a target with no style prop rejects style
* fix(types): make MakeAttrsOptional short-circuit when there are no attrs
The guard was `keyof K extends never`, but `K` is the set of attrs keys
and is `never` for any component without `.attrs()`. `keyof never` is
`string | number | symbol`, so the short-circuit never fired: every such
component instantiated an omit plus a `Partial<Pick<...>>` that removed
and re-added nothing, and intersected the empty object into its own
props, which never reduces.
Present since well before this branch. Removing it drops instantiations
by about 15% and check time by about 10% on top of the rest, and roughly
halves the length of the type shown on hover.
* refactor(types): name conditional branches so hovers stay readable
A conditional type alias loses its name the moment it resolves: the
checker returns the branch type and drops the aliasSymbol, so an inlined
branch prints its full expansion in every hover, error and quick-info.
Naming the branches (WithCSSVars, IntrinsicProps, ComponentTargetProps,
Substituted) gives the checker something to print. A styled button's
type goes from roughly 380 characters of nested FastOmit, Omit and
inline object literals to:
IStyledComponentBase<"web", Substituted<IntrinsicProps<"button">,
{ foo: boolean; }>> & string
The intrinsic branch applies the widening directly instead of routing
through OverrideStyle, since every intrinsic element declares `style`
and the guard has nothing to decide there.
Structural only. Types and instantiations move by well under a tenth of
a percent, and check time is unchanged.
* refactor(types): harden the consumer type-check budget
The budget could not see the regression class it exists to catch, and one
of its own flags silently measured the wrong thing.
- `--count=500` never matched, because the flag was parsed with indexOf
against a bare `--count`. That spelling measured the default 100 and
reported success. Now on util.parseArgs, which also rejects unknown and
valueless flags rather than ignoring them.
- Budget memory alongside types and instantiations. Against one fixture
6.4.4 records fewer instantiations than 6.4.3 while using ~190MB more,
so a counters-only budget reads that regression as an improvement.
Tolerances now come from measured run-to-run noise (counters are
bit-identical, memory moves ~1%) and the V8 heap is pinned so a slower
CI runner measures the same figures.
- Store the measured values plus a tolerance rather than bare ceilings,
so an improvement is reported instead of silently becoming slack.
- Record the typescript and @types/react versions and warn on drift,
since a dependency bump moves every figure on its own.
- Add a canary to the fixture. skipLibCheck hides a dist whose own
declarations cannot resolve their dependencies: every export degrades
to `any`, the fixture still compiles, and the run reports a large fake
win. The canary's @ts-expect-error directives stop firing in that
state, which the clean-compile gate catches.
- Cover the native entry and spread/generic call sites, and refuse to
measure against a dist older than src.
- One tsc invocation instead of two; --extendedDiagnostics already
prints the error lines the first pass was spawned to collect.
Also drops a dead React import left behind when styled.tsx moved to
TargetProps.
* feat(types): merge a declared style type instead of replacing it
Declaring `styled.div<{ style?: { width: number } }>` previously had no
effect, because the CSS-variable widening was applied after the
component's own props. Widening at the target fixed that but swung too
far: the declaration replaced the whole type, so constraining one field
lost every field the author had not mentioned.
The merge is the intersection that falls out of not omitting `style`
from the target, so `CSSPropertiesWithVars & { width: number }`
constrains width and keeps the rest. Both conditional spellings were
tried and measured first: testing `keyof A` tips tsc into TS2590
outright, and testing `keyof B` costs +54% types because it stays
deferred while B is generic and the checker materializes both branches.
The intersection costs +0.006%.
Full override stays expressible: a field declared `never` is ablated,
and the new exported CustomStyle<T> ablates everything a declaration
does not name, so nobody hand-writes `?: never` for 265 properties.
Also fixes a TS2589 in chained `.attrs()` that this branch introduced
against both 6.4.2 and 6.4.4. The `.attrs()` seam resolves its target
through ComponentPropsWithRef rather than TargetProps: a function-form
`.attrs(({ as }) => ({ as: as || 'button' }))` makes that target a
union, and TargetProps is two conditionals, so it distributes inside a
distribution. Measured on a three-line repro, 6.4.2 cost 157K
instantiations and TargetProps cost 6.9M, tipping into TS2589 with one
more chained layer; ComponentPropsWithRef lands it at 133K. It is
merged rather than substituted there so the widening survives.
Found by an adversarial battery built from 41 reported type issues,
compiled against 6.4.2, 6.4.4 and this branch on @types/react 18 and
19. Zero regressions and zero pinned-behavior drift across the set.
* fix(types): decide target permissiveness from the target, not the prop bag
Wrapping a target whose props cannot be introspected (Mantine's
polymorphic-factory components, and anything else whose resolved props
are `{}`) makes the styled component permissive, so the target's own
props and `children` keep working. Adding a prop of your own switched
that off:
styled(PolyButton)<{ $variant: 'a' | 'b' }>``
`WidenUntypedProps` asks whether the finished prop bag is empty, and a
transient prop gives it a `keyof` of `'$variant'`, so the widening
stopped applying and `children` started being rejected. Whether a target
can be introspected is a property of the target, not of what the
component layers on top, so the test now runs against the target.
Applying it over an already-widened bag is a no-op: the index signature
makes `keyof` be `string`, so the second check is false.
Reported in #5756 and still present on 6.4.2 and 6.4.4. Found by the
adversarial battery, which had it as the one case failing identically
everywhere rather than as a regression.
* refactor(types): drop the duplicated recursive branch in Interpolation
`RuleSet<Props>` is defined as `Interpolation<Props>[]`, so listing both
`RuleSet<Props>` and `Interpolation<Props>[]` in the union spelled the
same recursive branch twice and doubled the work of expanding it.
Keeping the named alias, which also reads better in hovers.
Found while investigating #3496, where `css?: CSSProp` plus a library
with deep recursive generics of its own trips the instantiation-depth
limit. The dedupe does not fix that on its own and no shallower
`CSSProp` is worth having: every variant that clears it also stops
`css={cssHelperOutput}` being assignable, which is the primary use of
the prop. The limitation reproduces identically on 6.4.2 and 6.4.4, so
it is standing rather than new; AGENTS.md records the ablation so it is
not re-litigated.
* fix(types): decide permissiveness from the target, and hold style constraints through `as`
Two gaps a full review found, both in code this branch introduced.
Permissiveness for an un-introspectable target was tested against the
merged prop bag rather than the target. Those coincide until `.attrs()`,
after which the bag has absorbed the component's own props, its `keyof`
stops being `never`, and the widening switches off -- #5756 one layer
down. Now tested against `TargetProps<Target>`, which is that parameter's
own default, so it costs no new instantiation. `WidenUntypedProps`
collapses into `WidenForUntypedTarget<P, P>`; the two were identical
apart from which parameter they tested.
`CustomStyle` promises its type is the only one accepted, and a declared
`style` promises the fields it names are constrained. Both were escapable
by rendering through `as` or `forwardedAs`, because
`PolymorphicComponentProps` substituted the render target's props over
the component's own and substitution replaces `style` outright. It merges
now. This is the one place a per-JSX-site cost was accepted rather than
moved off the call path, so it was measured first: +0.016% types, +0.48%
instantiations, memory unchanged.
Known limitation, documented on the type and in the changeset rather than
paid for: under `exactOptionalPropertyTypes` the intersection leaves no
`undefined` arm, so a component declaring its own `style` rejects an
explicit `style={undefined}`. Omitting the prop is unaffected and
`style?: X | undefined` restores it. Every automatic fix needs a
conditional in `MergeProps`, and that shape measured +54% types.
Also: names `MergeProps`'s taken branch so hovers print a name instead of
an expansion compounding once per extension link; aligns the `.attrs()`
implementation with its interface, which spelled the same position
differently while the comment explaining the correct spelling sat only on
one; and adds `--expose-gc` to the type-perf run, since tsc collects
before sampling memory only when `global.gc` exists and every figure
banked before this was a pre-GC snapshot including garbage. Memory is now
bit-identical across runs. A per-metric presence check closes a hole
where a metric absent from the budget file produced NaN bounds and
reported "within budget" while checking nothing.
* test(types): pin the reported type patterns as contract suites
Ports 29 cases from an adversarial battery built out of reported type
issues, using hand-written stubs rather than new dependencies.
Web: ref-callback inference, the interpolation parameter not widening to
`any`, attrs with a union prop and no `as const`, custom-element `as`
targets, event-handler and function-prop inference, prop extraction
through ReturnType, chained `.attrs({ as })`, custom properties in nested
object styles, computed-key selectors, withTheme, the v5-to-v6 alias
renames, and pins for the documented limitations.
Native: the package had no native type coverage at all, so a native-only
regression was invisible to the unit suites and the type check alike.
Covers `ref` on shorthand components including an unannotated ref
callback, attrs with a required prop, declared props reaching
interpolations, and the shorthand surface.
Four reported issues stay out of tree: antd, react-bootstrap 2.8,
react-spring and preact/compat are each a union-explosion or
recursion-depth cliff, and a simplified stub sits clear of the cliff and
passes for the wrong reason. Verified out of tree against the real
packages at the versions reported; AGENTS.md records which and when to
re-check.
The chained-attrs assertion was vacuous as first written: the function
form types the resolved target as the whole target union, which is
un-introspectable, so the permissive fallback accepted the prop being
asserted and would have accepted anything. Moved to the object form with
three controls.
* test(types): characterize the native style widening gap
A native `style` accepts web-only CSS (`float`, `'3em'`, custom
properties), because `TargetProps` carries no runtime parameter and so
cannot gate the CSS-variable widening on web vs native where it applies.
Verified identical on 6.4.2, 6.4.4 and current with a firing control in
every column, so this is inherited rather than introduced here. Closing
it means threading the runtime through `TargetProps` and its call sites,
which is a signature change to measure rather than a patch.
Raised as a suppressed comment on the PR review, which carries no comment
id and would otherwise be unfindable. Pinned so that if the gap ever
closes, the docs saying it is open get found.
* fix(types): gate the style widening on the runtime
TargetProps takes R as its first parameter and only ComponentTargetProps
consults it, since NativeTarget is AnyComponent and the intrinsic arm is
unreachable on native. R is deliberately undefaulted: a default is what
would let a future native call site pick web CSS up by omission.
The conditional distributes over Runtime, two members and concrete at
every entry point, so it costs +0.55% instantiations and +0.05% types
with memory flat -- not the ~4x a conditional over the target union
costs.
styled.View accepted `float` and custom properties on 6.4.2 through
6.4.4 alike; both are now pinned as @ts-expect-error in the native
contract suite. `width: '3em'` stays accepted and is not ours:
@types/react-native 0.71 types FlexStyle['width'] as `number | string`.
The prior characterization block cited it as evidence of this library's
widening, which it never was.
Claude-Session: https://claude.ai/code/session_01PSMbXaMtE84Gzk7ebfjBuK
* docs(types): update TargetProps references to the two-parameter form
Three comments still spelled the pre-runtime-gate signature. Copilot
flagged the one in types.ts; a repo-wide sweep for the same mistake found
two more in AGENTS.md, one of which described the distribution rule in a
way that now reads as forbidding the R gate.
Claude-Session: https://claude.ai/code/session_01PSMbXaMtE84Gzk7ebfjBuK
* docs: correct stale claims found by a repo-wide sweep
Verified mechanically rather than by reading, each with a control:
- docs/rendering-flow.md named buildClassName and rawElement, neither of
which exists. The diagram also claimed a React.createElement bypass;
`git log -S rawElement` finds nothing and every $$typeof use is type
detection, so that optimization is not on this branch. Replaced with
buildPropsForElement plus React's own createElement, and the AGENTS.md
perf row now says the raw-element form is a measurement, not an
inventory entry.
- The cast in styled.tsx was said to avoid "120" Styled<> instantiations
in two places; domElements has 153 entries. Restated per-element so it
cannot drift again.
- AGENTS.md documented `pnpm run generateErrors`, which fails from the
repo root. Every other command there is --filter scoped.
- PolymorphicCallProps' comment still described substituting the `as`
target's props, contradicting AGENTS.md, which records that they merge.
- The repo-root src/utils/errors.md was described as kept in sync. It is
read by nothing, stops at error 13, and its entry 2 describes a
different error than the one shipped. Documented as a frozen stub;
whether it should exist is left to the maintainer.
- The three-term server check has one deliberate two-term exception in
createGlobalStyle, now recorded so nobody relaxes the rule elsewhere.
Also enables noUnusedLocals, which is what would have caught the stale
Substitute import removed here. Contract suites opt out: a compile-only
type test declares things to be checked, not read.
Claude-Session: https://claude.ai/code/session_01PSMbXaMtE84Gzk7ebfjBuK1 parent 2949923 commit dfe4baf
18 files changed
Lines changed: 1592 additions & 191 deletions
File tree
- .changeset
- docs
- packages/styled-components
- scripts
- src
- constructors
- native
- test
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | 1 | | |
2 | | - | |
| 2 | + | |
3 | 3 | | |
4 | 4 | | |
5 | | - | |
| 5 | + | |
Large diffs are not rendered by default.
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
67 | 67 | | |
68 | 68 | | |
69 | 69 | | |
70 | | - | |
71 | | - | |
72 | | - | |
| 70 | + | |
| 71 | + | |
| 72 | + | |
73 | 73 | | |
74 | 74 | | |
75 | 75 | | |
| |||
0 commit comments