Skip to content

Commit 3de03c2

Browse files
authored
perf(types): faster type-checking for annotated styled component exports (#5801)
* perf(types): speed up type-checking of annotated styled component exports PolymorphicComponent extended React.ForwardRefExoticComponent, which drags in the defaultProps/propTypes/$$typeof relation that TypeScript re-checks at every annotated declaration site. Extending React.NamedExoticComponent instead drops that inherited cost while keeping the same call signature and ref forwarding. defaultProps and propTypes are re-declared on the interface so nothing about the emitted type changes for consumers. propTypes is typed as `any` (matching React 19's own base component) rather than WeakValidationMap, which @types/react removed in v19, so the declaration compiles for both React 18 and 19 consumers. Consumer budgets drop ~10%; intrinsic-tag and union-prop annotations fall furthest. * test(types): gate emitted declarations against supported @types/react majors The type-contract suite only compiles against the pinned @types/react 18, so a name that exists there but was removed on a newer major (as WeakValidationMap was on 19) can ship into dist unnoticed and break every strict React 19 consumer's build. test:types:dist compiles the built .d.ts under skipLibCheck: false against the minimum and maximum supported @types/react majors, failing on any diagnostic located in the package's own dist/. The maximum major installs into a gitignored, path-scoped folder so a second @types/react never enters the repo's ambient type set; each run checks exactly one major, chosen by explicit paths, and prints the resolved version. Wired into CI after the type-perf checks. * docs(agents): record type-only semver rules and the declaration gate command An additive type change ships as a patch (it cannot break a consumer's build); a breaking type change is bumped as a breaking change even though no runtime code moved. Also documents test:types:dist so the cross-major declaration gate is discoverable.
1 parent 7ce6aea commit 3de03c2

10 files changed

Lines changed: 265 additions & 20 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+
Type-checking is faster when you annotate exported styled components with an explicit type, the pattern that packages emitting their own declaration files (including any project using `isolatedDeclarations`) rely on. The improvement is largest in codebases that annotate many components built on intrinsic tags such as `styled.div`, `styled.span`, and `styled.button`, and wrappers over polymorphic components whose props are a union.
6+
7+
Nothing about the styled component's type changes for your code: props, `defaultProps`, `propTypes`, ref forwarding, and `as` polymorphism all behave exactly as before. This is purely a type-check speedup.

‎.github/workflows/test.yml‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,11 @@ jobs:
4848
- run: pnpm --filter styled-components type-perf
4949
# The `data-*`-augmented path has its own cost and budget (see #5796).
5050
- run: pnpm --filter styled-components type-perf:augment
51+
# Guards that the emitted .d.ts compiles under `skipLibCheck: false` against
52+
# the min and max supported `@types/react` majors. The contract suite only
53+
# runs on the pinned 18, so a name removed in a newer major (e.g.
54+
# `WeakValidationMap` on 19) otherwise ships straight into `dist`.
55+
- run: pnpm --filter styled-components test:types:dist
5156
test:
5257
runs-on: ubuntu-latest
5358
steps:

‎.gitignore‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ update-dynamic-styles-trace.json
1919
.rollup.cache
2020
# Generated consumer fixture for the type-check budget (`pnpm --filter styled-components type-perf`)
2121
.type-perf
22+
# Generated tsconfigs for the published-declaration gate (`pnpm --filter styled-components test:types:dist`)
23+
.type-check-dist
2224
.build
2325
.next
2426
.expo

‎AGENTS.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ mapped below.
4141
## Agent Rules
4242

4343
- Create changesets only for user-visible changes (bug fixes, features, breaking changes). Skip internal refactors, build tooling, and test changes. Also skip changesets for fixes to code introduced within the same unreleased version (no user ever saw the bug).
44+
- Semver for type-only changes: an ADDITIVE type change (a new exported type, a new optional member, a widened input) ships as a patch, never a minor -- it cannot break a consumer's build, so a code-review or semver tool flagging a new type export as under-versioned is wrong here. A BREAKING type change (removing an exported type or member, narrowing a type, changing a signature consumers rely on) is a breaking change and is bumped as one; it is not a patch just because no runtime code moved.
4445
- Changeset descriptions AND PR descriptions are both consumer-facing. Write so someone who uses the library but hasn't read its source can understand the change -- describe what the user observes change in their app. NO internal API names (`rebuildGroup`, `clearRules`, `instanceRules`, `useLayoutEffect`, `rulesEqual`, etc.), NO mechanism descriptions ("the cleanup effect now runs on..."), NO references to specific code paths. Implementation details belong in commit message bodies and the `docs/` specifications, never in changesets or PR bodies.
4546
- Do not edit CHANGELOG.md -- it is auto-generated by changesets
4647
- Always run the formatter (`pnpm --filter styled-components prettier`) before committing code changes
@@ -59,6 +60,7 @@ mapped below.
5960
- `pnpm --filter styled-components test:web` -- Test web build
6061
- `pnpm --filter styled-components test:native` -- Test React Native
6162
- `pnpm --filter styled-components test:types` -- Type contract suites (compile-only, no runner)
63+
- `pnpm --filter styled-components test:types:dist` -- Compile the emitted `.d.ts` under `skipLibCheck: false` against the min and max supported `@types/react` majors (needs `pnpm build` first). The contract suite only covers the pinned 18; this catches a name removed in a newer major before it ships.
6264
- `pnpm --filter styled-components type-perf` -- Consumer type-check budget (needs `pnpm build` first)
6365
- `pnpm --filter styled-components bench` -- Run all benchmarks (web + native + RSC)
6466
- `pnpm --filter styled-components bench:web` -- Run web benchmarks

‎docs/type-performance.md‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,55 @@ which omits `style` and lands further from identity -- for an identity-cheap rel
222222
means plain hand annotations no longer need it. The `annotated` fixture kind guards the axis so a future
223223
deepening of this relation is caught.
224224

225+
The widening is not the largest part of that relation, and the residual above is not fully inherent. The
226+
`style` ablation floor stands, but the component interface carried removable cost on top of it:
227+
`PolymorphicComponent` extended `React.ForwardRefExoticComponent<P>`, which adds two members over
228+
`React.NamedExoticComponent<P>` -- `defaultProps?: Partial<P>` and `propTypes?: WeakValidationMap<P>` --
229+
each a mapped type over the FULL widened prop bag (~265 keys on an intrinsic tag). `Props` is invariant, so
230+
at every explicit declaration-site annotation those two mapped members are walked both directions, per
231+
structurally-unique component, and they dominate the relation: dropping them by extending
232+
`NamedExoticComponent` instead measured -44% on an intrinsic-tag annotation fixture and ~-10% on the
233+
consumer budget (`type-perf.budget.json` holds the live figures; do not restate them here). The cost is the
234+
per-component PARAMETERIZATION, not the members themselves: both are re-declared in shapes that do not
235+
depend on the per-component bag, so `PolymorphicComponent` keeps both public members and the change removes
236+
nothing (it is not a breaking type change).
237+
238+
- `defaultProps?: Partial<BaseProps>` is free: `IStyledComponentBase` re-declares `defaultProps`
239+
(`ExecutionProps & Partial<Props>`), so its override shadows this base member on any actual styled
240+
component and it is never walked at a declaration-site relation (measured zero delta).
241+
- `propTypes?: any` replaces the inherited `WeakValidationMap<P>`. It must be `any`, not
242+
`WeakValidationMap<...>`: `@types/react` 19 removed `WeakValidationMap` (its `ForwardRefExoticComponent`
243+
now declares `propTypes?: any`), and the peer range is `react >= 16.8.0` with no upper bound, so any
244+
reference to `React.WeakValidationMap` publishes a `TS2694` into every React 19 consumer's build -- the
245+
one spelling that resolves across the whole supported range is `any`. It is also a fixed type, so the
246+
relation short-circuits, whereas the per-component `WeakValidationMap<widened-bag>` it replaced was the
247+
dominant declaration-site cost; and it stays assignable both directions a consumer uses, so the member is
248+
kept, not narrowed. Keeping it rather than dropping it costs well under +1% on the consumer budget, the
249+
price of staying non-breaking. The type-contract suite runs only against the pinned `@types/react` 18, so
250+
a cross-version hazard like this is invisible to it; `pnpm --filter styled-components test:types:dist` is
251+
the guard, compiling the emitted `.d.ts` under `skipLibCheck: false` against the min and max supported
252+
`@types/react` majors and failing on any diagnostic in the library's own `dist/`.
253+
254+
Ref forwarding is unaffected: the ref rides in the call-site props via `React.ComponentPropsWithRef` inside
255+
`TargetProps`, not in the exotic base. Soundness is preserved because the swap touches only covariant OUTPUT
256+
positions; the call-signature input contract that rejects a bad prop, an unknown prop, or a wrong ref
257+
element is untouched, all pinned in the contract suite.
258+
259+
Two `Partial<Props>` members over the same bag remain, the library's own: `IStyledComponentBase`'s
260+
`defaultProps` and `CommonStatics.attrs` (`Attrs<Props>` carries `Partial<Props>` in each arm). Loosening
261+
both together -- `defaultProps?: ExecutionProps` and `attrs: Attrs<any>[]` -- measured a further step down
262+
on the same fixture, but only together (while either stays precise its `Partial<Props>` still forces the
263+
full-bag walk, so loosening one alone is nearly free of benefit). It is deliberately NOT taken: it trades
264+
away the read precision of `.defaultProps` and `.attrs`, which are part of the public statics contract, for
265+
a gain on an axis that only bites codebases annotating many intrinsic-tag exports. Revisit only with that
266+
break accepted, and measure the pair, never one.
267+
268+
`withTheme`'s return type (`hoc/withTheme.tsx`) is the same `ForwardRefExoticComponent` base over a wrapped
269+
component's prop bag, and was left as `ForwardRefExoticComponent`. The cost there is paid once when
270+
`withTheme` itself compiles, not multiplied across every styled component, and the return is rarely
271+
annotated in bulk, so the swap buys nothing measurable and would drop `propTypes` typing from a
272+
long-released signature for no reason.
273+
225274
## The empty-prop-bag guard in Substitute and MergeProps
226275

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

‎packages/styled-components/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
"pretest": "pnpm run generateErrors",
2525
"test": "pnpm run test:web && pnpm run test:native && pnpm run test:types",
2626
"test:types": "tsc --noEmit --project tsconfig.test-types.json && tsc --noEmit --project tsconfig.test-template-index.json",
27+
"test:types:dist": "node scripts/typeCheckDist.mjs",
2728
"type-perf": "node scripts/typePerf.mjs",
2829
"type-perf:augment": "node scripts/typePerf.mjs --augment",
2930
"test:web": "jest -c jest.config.main.js",
Lines changed: 153 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,153 @@
1+
#!/usr/bin/env node
2+
/**
3+
* Published-declaration gate.
4+
*
5+
* A library's emitted `.d.ts` is public contract: it must compile for a consumer
6+
* on any supported peer version and any reasonable tsconfig, never forcing a
7+
* setting (skipLibCheck, a specific @types version) to dodge errors that
8+
* originate in the library's OWN types. The type-contract suite only runs against
9+
* the pinned `@types/react` 18, so a name that exists there but not on a newer
10+
* major slips straight into `dist` -- `propTypes?: React.WeakValidationMap<P>`
11+
* compiled clean on 18 and shipped a `TS2694` into every strict React 19
12+
* consumer's build (`WeakValidationMap` was removed on `@types/react` 19).
13+
*
14+
* This checks the built declarations under `skipLibCheck: false` against the
15+
* minimum and maximum supported `@types/react` majors, failing on any diagnostic
16+
* located in the package's own `dist/`. Errors inside dependency `.d.ts`
17+
* (react-native, node/dom global collisions) are filtered out: they are
18+
* pre-existing ecosystem conflicts, not this library's contract, and letting them
19+
* through would both mask a real break and manufacture false ones. `skipLibCheck:
20+
* true` is NOT a valid gate here -- it suppresses the very declaration errors this
21+
* catches (verified: the WeakValidationMap break reports zero errors under it).
22+
*
23+
* Isolation matters, and is why the peer majors are NOT project devDependencies.
24+
* The repo pins `@types/react` 18; adding a second copy under `node_modules/@types`
25+
* would make TypeScript auto-include BOTH majors' ambient globals into every normal
26+
* type-check at once (the repo leaves `types` unset), so "which React is in scope"
27+
* would be both, and only `skipLibCheck: true` would hide the resulting global
28+
* collisions. Instead the min resolves from the project's own pinned copy and the
29+
* max is installed into a gitignored, path-scoped folder that no other tsconfig
30+
* sees. Each run compiles against EXACTLY ONE major, chosen by explicit `paths`
31+
* with `types: ['node']` so no `@types/react` is ambiently included, and prints the
32+
* resolved version so the log always says what was tested.
33+
*
34+
* Requires `pnpm build` first.
35+
*/
36+
import { execFileSync } from 'node:child_process';
37+
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
38+
import { createRequire } from 'node:module';
39+
import { dirname, join, relative, resolve } from 'node:path';
40+
import { fileURLToPath } from 'node:url';
41+
42+
const require = createRequire(import.meta.url);
43+
const pkgRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');
44+
const distDir = join(pkgRoot, 'dist');
45+
const workDir = join(pkgRoot, '.type-check-dist');
46+
const tscPath = require.resolve('typescript/lib/tsc.js');
47+
48+
if (!existsSync(join(distDir, 'index.d.ts'))) {
49+
console.error('type-check-dist: dist/index.d.ts missing -- run `pnpm build` first.');
50+
process.exit(1);
51+
}
52+
53+
// The maximum-major @types to test, pinned so a run is deterministic and the log
54+
// says exactly what was checked. Bump deliberately when raising the supported
55+
// ceiling; the minimum comes from the project's own pinned `@types/react`.
56+
const MAX = { react: '@types/[email protected]', reactDom: '@types/[email protected]' };
57+
58+
const pkgDir = spec => dirname(require.resolve(`${spec}/package.json`));
59+
const versionAt = dir => JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')).version;
60+
61+
/** Install the max-major @types into a path-scoped folder no other tsconfig sees. */
62+
function isolatedMax() {
63+
const root = join(workDir, 'max');
64+
if (!existsSync(join(root, 'node_modules', '@types', 'react', 'package.json'))) {
65+
mkdirSync(root, { recursive: true });
66+
writeFileSync(join(root, 'package.json'), '{"private":true}\n');
67+
execFileSync('npm', ['install', '--no-save', '--no-package-lock', MAX.react, MAX.reactDom], {
68+
cwd: root,
69+
stdio: 'ignore',
70+
});
71+
}
72+
const nm = join(root, 'node_modules', '@types');
73+
return { react: join(nm, 'react'), reactDom: join(nm, 'react-dom') };
74+
}
75+
76+
// Only react/react-dom are pinned per target; csstype, @types/node, stylis and
77+
// react-native resolve the normal way so the two runs differ by exactly the
78+
// surface under test. `types: ['node']` keeps @types/node's ambient globals
79+
// (dist references the NodeJS namespace) while excluding every @types/react from
80+
// the ambient set, so the React in scope is purely what `paths` names.
81+
function configFor(react, reactDom) {
82+
return {
83+
compilerOptions: {
84+
baseUrl: pkgRoot,
85+
jsx: 'react-jsx',
86+
lib: ['ES2021', 'DOM'],
87+
module: 'ESNext',
88+
moduleResolution: 'bundler',
89+
noEmit: true,
90+
paths: {
91+
react: [react],
92+
'react/jsx-runtime': [join(react, 'jsx-runtime')],
93+
'react/jsx-dev-runtime': [join(react, 'jsx-dev-runtime')],
94+
'react-dom': [reactDom],
95+
'react-dom/server': [join(reactDom, 'server')],
96+
'react-dom/client': [join(reactDom, 'client')],
97+
},
98+
skipLibCheck: false,
99+
strict: true,
100+
target: 'ES2020',
101+
types: ['node'],
102+
},
103+
// Both published entry points; the native entry is what pulls react-native in.
104+
files: [join(distDir, 'index.d.ts'), join(distDir, 'native', 'index.d.ts')],
105+
};
106+
}
107+
108+
/** Lines like `path/to/file.d.ts(12,5): error TS2694: ...`; keep only own-dist ones. */
109+
function ownDistErrors(output) {
110+
const out = [];
111+
for (const line of output.split('\n')) {
112+
const m = /^(.*\.d\.ts)\(\d+,\d+\): error TS/.exec(line);
113+
if (!m) continue;
114+
const abs = resolve(pkgRoot, m[1]);
115+
if (abs.startsWith(distDir)) out.push(` ${relative(pkgRoot, abs)}${line.slice(m[1].length)}`);
116+
}
117+
return out;
118+
}
119+
120+
mkdirSync(workDir, { recursive: true });
121+
122+
const min = { react: pkgDir('@types/react'), reactDom: pkgDir('@types/react-dom') };
123+
const max = isolatedMax();
124+
const targets = [
125+
{ kind: 'min', ...min },
126+
{ kind: 'max', ...max },
127+
];
128+
129+
let failed = false;
130+
for (const target of targets) {
131+
const cfg = join(workDir, `tsconfig.${target.kind}.json`);
132+
writeFileSync(cfg, `${JSON.stringify(configFor(target.react, target.reactDom), null, 2)}\n`);
133+
134+
let output = '';
135+
try {
136+
execFileSync(process.execPath, [tscPath, '-p', cfg], { encoding: 'utf8' });
137+
} catch (error) {
138+
output = `${error.stdout ?? ''}${error.stderr ?? ''}`;
139+
}
140+
141+
const label = `@types/react ${versionAt(target.react)}`;
142+
const errors = ownDistErrors(output);
143+
if (errors.length) {
144+
failed = true;
145+
console.error(`type-check-dist: ${label} -- ${errors.length} error(s) in dist/:`);
146+
console.error(errors.join('\n'));
147+
} else {
148+
console.log(`type-check-dist: ${label} -- dist declarations compile clean`);
149+
}
150+
rmSync(cfg, { force: true });
151+
}
152+
153+
process.exit(failed ? 1 : 0);

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

Lines changed: 40 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -348,20 +348,46 @@ type PolymorphicCallProps<
348348
* props from the given rendering target to get proper typing for
349349
* any specialized props in the target component.
350350
*/
351-
export interface PolymorphicComponent<
352-
out R extends Runtime,
353-
in out BaseProps extends BaseObject,
354-
> extends React.ForwardRefExoticComponent<
355-
// FastOmit ahead of the intersection so a wrapped component's own `as` /
356-
// `forwardedAs` props (e.g. Next.js Link's `as?: Url`) don't intersect with
357-
// our `WebTarget`-typed versions and produce conflicting required-shape
358-
// types (#5734). `React.ComponentProps<typeof StyledComponent>` still
359-
// surfaces our `as` / `forwardedAs` (the original #5654 fix).
360-
FastOmit<BaseProps, 'as' | 'forwardedAs'> & {
361-
as?: StyledTarget<R> | undefined;
362-
forwardedAs?: StyledTarget<R> | undefined;
363-
}
364-
> {
351+
export interface PolymorphicComponent<out R extends Runtime, in out BaseProps extends BaseObject>
352+
// `NamedExoticComponent`, not `ForwardRefExoticComponent`: the latter adds
353+
// `defaultProps?: Partial<P>` and `propTypes?: WeakValidationMap<P>`, each a
354+
// mapped type over the full widened prop bag `P`. Under the invariant `Props`
355+
// those two members are walked both directions at every explicit declaration-site
356+
// annotation (`StyledComponent<Tag, P>` / `IStyledComponent<...>`), and on an
357+
// intrinsic tag the bag is ~265 keys, so that per-component parameterization
358+
// dominates the relation's cost (measured -44% on an intrinsic-tag annotation
359+
// fixture, ~-10% on the consumer budget, by removing it). Both members are then
360+
// re-declared just below in shapes that are NOT parameterized per component, so
361+
// they stay on this public type (nothing is removed, so the change is not a
362+
// breaking one) while relating cheaply. Ref forwarding is unaffected either way:
363+
// the ref rides in the call-site props via `ComponentPropsWithRef` in
364+
// `TargetProps`, not in the exotic base. See docs/type-performance.md.
365+
extends React.NamedExoticComponent<
366+
// FastOmit ahead of the intersection so a wrapped component's own `as` /
367+
// `forwardedAs` props (e.g. Next.js Link's `as?: Url`) don't intersect with
368+
// our `WebTarget`-typed versions and produce conflicting required-shape
369+
// types (#5734). `React.ComponentProps<typeof StyledComponent>` still
370+
// surfaces our `as` / `forwardedAs` (the original #5654 fix).
371+
FastOmit<BaseProps, 'as' | 'forwardedAs'> & {
372+
as?: StyledTarget<R> | undefined;
373+
forwardedAs?: StyledTarget<R> | undefined;
374+
}
375+
> {
376+
// Preserved from the old `ForwardRefExoticComponent` base. `defaultProps` is
377+
// free: `IStyledComponentBase` re-declares it (`ExecutionProps & Partial<Props>`),
378+
// so on an actual styled component this base member is shadowed and never walked
379+
// at a declaration-site relation. `propTypes` is `any` -- exactly what React's own
380+
// `ForwardRefExoticComponent` declares on `@types/react` 19, which dropped the old
381+
// `WeakValidationMap<P>`. `any` is the only spelling that resolves across the whole
382+
// supported peer range (16.8+): `React.WeakValidationMap` does not exist on
383+
// `@types/react` 19 and referencing it publishes a `TS2694` into every React 19
384+
// consumer's build. It is also a fixed type, so the relation short-circuits (that
385+
// per-component `WeakValidationMap<BaseProps>` was the dominant declaration-site
386+
// cost), and it stays assignable both directions a consumer uses, so the member is
387+
// kept, not narrowed. Cost of the pair vs dropping both: ~+0.4% on the consumer
388+
// budget, well worth keeping the change non-breaking.
389+
defaultProps?: Partial<BaseProps> | undefined;
390+
propTypes?: any;
365391
// A single call signature, not overloads: with overloads a mid-typed JSX
366392
// attribute matches none, resolution fails, and attribute completion drops. The
367393
// prop-shape branching lives in `PolymorphicCallProps`.

‎packages/styled-components/type-perf.augment.budget.json‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
{
22
"count": 100,
33
"measured": {
4-
"instantiations": 895632,
5-
"memoryKb": 201742,
6-
"types": 38232
4+
"instantiations": 812680,
5+
"memoryKb": 197818,
6+
"types": 37045
77
},
88
"tolerancePct": {
99
"instantiations": 10,

0 commit comments

Comments
 (0)