Skip to content

Commit 00b9ee2

Browse files
authored
fix(types): cheaper annotated declaration sites, and sound generic polymorphic props (#5794)
* fix(types): cheaper annotated declaration sites, and narrow generic polymorphic 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. * perf(types): `.attrs` target-unchanged fast path, and broaden the type-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. * perf(types): distribute `MakeAttrsOptional` over built-in `Omit` 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.
1 parent ff15a53 commit 00b9ee2

9 files changed

Lines changed: 381 additions & 46 deletions

File tree

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
'styled-components': patch
3+
---
4+
5+
`.attrs()` is cheaper to type-check.
6+
7+
Two costs on the `.attrs` path are gone. Object-form `.attrs()` left the rendered target unchanged but still re-resolved that target's whole prop bag on every call, making `.attrs` on an HTML or SVG tag far costlier than on a wrapped component; it now reuses the props already resolved for the tag. Separately, making attrs-provided keys optional ran an avoidably expensive pass over the target's full prop set on every attrs component. Together these cut consumer type-check work measurably across every `.attrs` form, with no change to the resulting component's accepted props. Redirecting the target with `.attrs({ as })`, including the function form, is unaffected.
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
---
2+
'styled-components': patch
3+
---
4+
5+
Explicitly annotated styled components type-check faster.
6+
7+
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 be several times more expensive to check than an inferred one, because the annotation's `style` and the component's widened `style` were two different csstype representations that the checker compared property by property.
8+
9+
The inline `style` widening now builds on React's own `CSSProperties`, the same type a hand-written annotation carries, so that comparison short-circuits. On a 40-component fixture this cut the types created for the annotated pattern by about 21%, with no change to what `style` accepts: CSS custom properties, a component's own narrow `style`, and `style={undefined}` all behave exactly as before.
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
'styled-components': patch
3+
---
4+
5+
`styled()` wrapping a generic polymorphic component keeps its declared props narrow.
6+
7+
Wrapping a component whose props are generic over an element type, such as the common `<C extends React.ElementType>(props: PolymorphicProps<C, OwnProps>)` pattern, 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. The wrapper now narrows those props exactly as the direct component does, so a bad value is caught in both places. Valid props, children, and plain (non-generic) targets are unaffected.

‎docs/type-performance.md‎

Lines changed: 100 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,26 @@ correctness canary sitting inside the perf gate. It is also the single most expe
3939
component, by a wide margin, so adding it moved the recorded budget substantially on its own. That jump
4040
was fixture growth, not a regression.
4141

42+
The `annotated` kind prices the declaration site rather than the call site: a `styled.div` result
43+
assigned to an explicit `IStyledComponent<'web', FastOmit<DivProps, never> & …>` annotation whose prop
44+
bag is hand-written instead of the shape the library computes. This is what isolatedDeclarations and any
45+
`.d.ts`-emitting package produce, and it is the one place the style widening costs rather than saves
46+
(see "The declaration-site relation" below). No other kind annotates a result, so without it a change
47+
that deepened that relation would move nothing here. Like `unionTarget` it is expensive per component,
48+
so it too moved the recorded budget on its own -- fixture growth, not a regression.
49+
50+
Four exotic kinds each price a `types.ts` conditional arm no other kind reaches, and each also fails the
51+
clean-compile gate if its mechanism regresses, so they are correctness canaries sitting inside the perf
52+
gate the way `unionTarget` is: `permissiveFactory` (a Mantine-style un-introspectable target, the
53+
"Permissiveness for un-introspectable targets" section), `genericPoly` (a generic polymorphic target, the
54+
`string extends keyof P` gate under "The style widening"), `attrsAsRedirect` (function-form `.attrs` that
55+
redirects the target, the TS2589-sensitive seam under "Target prop resolution"), and `disjointTarget` (a
56+
no-shared-keys union target, "The empty-prop-bag guard"). Two call-site variants on `plainTag` price a
57+
relation no site otherwise triggers: passing `style` (the widening, from the call-site direction) and a
58+
`ref` callback (contextual inference, #5687). `canary.tsx` additionally pins the two soundness properties
59+
a cost kind cannot catch on its own: a `genericPoly` bad value is rejected, and a `permissiveFactory`
60+
arbitrary prop is accepted.
61+
4262
A kind added or a weight changed here changes what the budget means, so re-measure with `--update` and
4363
say in the commit that the fixture, not the cost, is what moved. `type-perf.budget.json` is the live
4464
figure; `pnpm --filter styled-components type-perf` prints the current one. Do not restate either here,
@@ -73,6 +93,30 @@ more chained layer, a hard failure against both 6.4.2 and 6.4.4 rather than a sl
7393
at 133K, below 6.4.2. Cheaper in count but deeper in nesting is a real trade, and this one position is
7494
where nesting wins.
7595

96+
That `ComponentPropsWithRef` re-merge runs only when `.attrs()` redirects the target. Object-form
97+
`.attrs()` (the common case) leaves the target unchanged, so `AttrsTarget` returns `Target`,
98+
`OuterProps` already equals `TargetProps<R, Target>`, and re-merging `ComponentPropsWithRef<Target>`
99+
rebuilds the ~265-key intrinsic bag only to reproduce what `OuterProps` held. A `[PrivateResolvedTarget]
100+
extends [Target]` fast path returns `MergeProps<OuterProps, Props>` directly for that case, keeping the
101+
function-form union on the `ComponentPropsWithRef` branch (the bracket stops it distributing here). It
102+
is the single largest per-kind cost in the fixture (`.attrs` on an intrinsic priced 27x `.attrs` on a
103+
component before this), and the fast path measured -6.8% instantiations on the 100-component fixture with
104+
the contract suite and every `.attrs` behavior unchanged.
105+
106+
The seam is not the largest part of the `.attrs` cost. Decomposing the chain, the `.attrs()` call itself
107+
is cheap; the explosion is in the final `IStyledComponent` production, where `MakeAttrsOptional` runs a
108+
mapped pass over the ~266-key widened intrinsic bag to make attrs-provided keys optional, per
109+
structurally-unique component (each bag differs by its own prop names, so nothing caches) -- about 30% of
110+
the types an `.attrs`-on-a-tag component creates. Its taken branch uses built-in `Omit` distributed
111+
through an outer `P extends unknown`, not `FastOmit`: built-in `Omit` is the more optimized here (the
112+
same result the `OverrideStyle` note records), and the distribution runs it per union member so a
113+
union-props attrs target (`styled(Pressable).attrs(...)`) keeps its member-specific keys rather than
114+
collapsing to the union's common ones (a bare undistributed `Omit` drops `href`). Measured: -7.5% types,
115+
-4.1% instantiations on the consumer fixture, memory flat, contract suite and every `.attrs` form
116+
unchanged. Note the union redirect above is NOT where the cost is: a union redirect and a single-concrete
117+
redirect price identically, and collapsing the `ComponentPropsWithRef` re-merge moves ~6 types while
118+
breaking four redirect contracts, so it stays.
119+
76120
## The style widening
77121

78122
The widening is web-only, gated on `TargetProps`' first parameter (`R extends Runtime`, deliberately
@@ -95,8 +139,20 @@ guard; every intrinsic element provably declares `style` (the set of `React.JSX.
95139
lacking it is `never`), so `IntrinsicProps` applies `WithCSSVars` directly rather than asking a question
96140
with one possible answer.
97141

98-
Five things are load-bearing about the current shape, each found by measurement:
99-
142+
Six things are load-bearing about the current shape, each found by measurement:
143+
144+
- `string extends keyof P` gates the widening off entirely for a prop bag carrying a `[k: string]: any`
145+
index signature, returning `P` untouched. A generic polymorphic component
146+
(`<C extends ElementType>(p: … & ComponentProps<C>)`) introspects at the `ElementType` constraint,
147+
where `ComponentProps<ElementType>` is `any`, so its extracted bag gains that index alongside its
148+
narrow props. `WithCSSVars`' `Omit<P, 'style'>` (`Pick<P, Exclude<keyof P, 'style'>>`) would then
149+
collapse every narrow key into the index (`keyof P` is `string`, `Exclude<string, 'style'>` is still
150+
`string`), widening a declared `variant: 'a' | 'b'` to `any` so `styled(Button)` accepts props the
151+
component itself rejects (#5756). Declining to widen keeps the narrow props; the only thing given up is
152+
custom-property widening on a `style` that is already `any`, which is moot. The key-preserving
153+
alternative, `FastOmit` in `WithCSSVars`, measured ~+11% instantiations on the 100-component fixture
154+
(the homomorphic-mapped-type price the intrinsic path avoids) and is rejected for that reason; the gate
155+
is instantiation-flat.
100156
- The test is `'style' extends keyof P`, not `P extends { style?: infer S }`. `{}` vacuously satisfies
101157
the latter, which would hand every un-introspectable target a `style` key and defeat
102158
`WidenUntypedProps` (regresses #5756).
@@ -117,6 +173,48 @@ Five things are load-bearing about the current shape, each found by measurement:
117173
downstream. Measured cost of adding it back: +47K types and +73% check time on a 100-component
118174
fixture. Never intersect `& {}` into a type that flows into prop bags.
119175

176+
## The declaration-site relation
177+
178+
Assigning a `styled` result to an explicit annotation --
179+
`const X: IStyledComponent<'web', FastOmit<DivProps, never> & P> = styled.div<P>` -- forces an
180+
assignability check between the inferred component and the hand-written type. The two prop bags differ in
181+
exactly one field, `style`: the widened `style` a `styled` result carries versus the plain `style` a
182+
consumer writes. `Props` is invariant (`in out`), so the check relates the two `style` types both ways,
183+
and the reverse direction is where the cost sits.
184+
185+
Keeping the widened `style` and a hand annotation's `style` on the SAME csstype instantiation is what
186+
makes that reverse relation cheap. {@link CSSPropertiesWithVars} bases on `React.CSSProperties` -- which
187+
is what a hand-written `style` is -- so `React.CSSProperties & Vars` relates to `React.CSSProperties` by
188+
the intersection-member fast path. Before this, the widened style based on the library's `CSSProperties`
189+
(`CSS.Properties<number | (string & {})>`), a different instantiation than the annotation's
190+
`CSS.Properties<string | number>`, so the checker walked `StandardProperties` / `VendorLonghandProperties`
191+
member by member, once per component. That was the whole of the 6.5.0 report from isolatedDeclarations
192+
packages. On a 40-component fixture the naive annotation cost 8,281 types before the rebase and 6,552
193+
after (−21%; instantiations 32,651 → 28,731), TS 5.9.3 / @types/react 18, with the call-site budget and
194+
the web+native type tests unmoved and every widening behavior preserved (custom properties,
195+
`style={undefined}` under `exactOptionalPropertyTypes`, a component's own narrow `style`, value
196+
rejection). Only the inline `style` prop rebases; object styles keep the richer numeric
197+
{@link CSSProperties} base.
198+
199+
Change ONLY the cached base. Rebasing it and also reshaping `WithCSSVars` in the same pass -- dropping the
200+
`(P[keyof P & 'style'] & {})` union arm, or swapping the `Omit<…, 'style'>` for a raw
201+
`IntrinsicElements[T] & { style }` intersection -- regresses declaration-site instantiations sharply
202+
(measured ~+46% and higher, a net loss) because the union arm is the forward-direction identity anchor
203+
and the `Omit` is what removes the target's own `style` before the widened one is added. The rebase wins
204+
on its own; the reshape does not, and the two were conflated in the pass that first tried this and wrongly
205+
recorded the whole idea as rejected.
206+
207+
The rebase narrows the divergence but cannot erase it: a divergent hand annotation cannot reach
208+
inferred-baseline cost, which needs reference-identity (annotating with `typeof` the component is free).
209+
Ablation on the same fixture: dropping the widening entirely
210+
(`IntrinsicProps = React.JSX.IntrinsicElements[T]`) lands at 2,385, so the residual over that floor is the
211+
`Omit` walk of the ~250 `HTMLAttributes` keys, inherent to any structural relation between two
212+
differently-built-but-equal bags. A consumer who still annotates explicitly should use the exact shape the
213+
constructor emits, `IStyledComponent<'web', MergeProps<TargetProps<'web', Tag>, P>>` -- not `Substitute`,
214+
which omits `style` and lands further from identity -- for an identity-cheap relation, but the rebase
215+
means plain hand annotations no longer need it. The `annotated` fixture kind guards the axis so a future
216+
deepening of this relation is caught.
217+
120218
## The empty-prop-bag guard in Substitute and MergeProps
121219

122220
Both aliases short-circuit to `A` when `B` contributes nothing, which keeps `FastOmit<A, never> & {}`

0 commit comments

Comments
 (0)