Skip to content

Commit 3470387

Browse files
fix: support template index signatures (#5797)
* fix: support template index signatures * fix(types): union widening for the data-* augmented path, and guard its cost Builds on the data-* template-literal index signature fix. - Widen the augmented intrinsic style through a FastOmit union rather than a plain intersection. A plain intersection forces style to require the custom property index, so an explicit IStyledComponent declaration-site annotation carrying plain CSSProperties no longer relates (a real TS2322). The union form mirrors the normal WithCSSVars widening and keeps that relation intact. - Cover the two cases the reporter flagged that the first patch left untested: the conditional call site (cond ? A : B) and the declaration-site annotation. - Add a --augment mode to typePerf.mjs, with its own budget file and a CI step, so the data-* path's type-check cost (and this regression) is guarded rather than invisible. The default fixture never exercises that path. - Document that the probe detects data-* only; other template prefixes still fall through to the standard widening. --------- Co-authored-by: cyphercodes <[email protected]> Co-authored-by: Evan Jacobs <[email protected]>
1 parent 8ebf40a commit 3470387

8 files changed

Lines changed: 181 additions & 15 deletions

File tree

‎.changeset/fuzzy-ravens-smile.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'styled-components': patch
3+
---
4+
5+
Fix TypeScript errors in projects that augment React HTML props with a `data-*` template-literal index signature.

‎.github/workflows/test.yml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,8 @@ jobs:
4646
# Guards consumer type-check cost against the built .d.ts. Regressions here
4747
# are invisible to the unit and type-contract suites (see #5767).
4848
- run: pnpm --filter styled-components type-perf
49+
# The `data-*`-augmented path has its own cost and budget (see #5796).
50+
- run: pnpm --filter styled-components type-perf:augment
4951
test:
5052
runs-on: ubuntu-latest
5153
steps:

‎packages/styled-components/package.json‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,9 @@
2323
"test:build": "jest -c jest.config.build.js",
2424
"pretest": "pnpm run generateErrors",
2525
"test": "pnpm run test:web && pnpm run test:native && pnpm run test:types",
26-
"test:types": "tsc --noEmit --project tsconfig.test-types.json",
26+
"test:types": "tsc --noEmit --project tsconfig.test-types.json && tsc --noEmit --project tsconfig.test-template-index.json",
2727
"type-perf": "node scripts/typePerf.mjs",
28+
"type-perf:augment": "node scripts/typePerf.mjs --augment",
2829
"test:web": "jest -c jest.config.main.js",
2930
"test:native": "jest -c jest.config.native.js --forceExit",
3031
"bench": "pnpm run bench:web && pnpm run bench:native && pnpm run bench:rsc",

‎packages/styled-components/scripts/typePerf.mjs‎

Lines changed: 62 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,26 @@
1414
* node scripts/typePerf.mjs check against the budget
1515
* node scripts/typePerf.mjs --update rewrite the budget from this run
1616
* node scripts/typePerf.mjs --count 500
17+
* node scripts/typePerf.mjs --augment measure the `data-*`-augmented path
18+
*
19+
* `--augment` injects the `data-${string}` template-literal index signature onto
20+
* `HTMLAttributes` that large apps add for arbitrary data attributes. That routes
21+
* every intrinsic element through a distinct `style` widening (#5796), a cost the
22+
* default fixture never exercises. It checks against its own budget file, so the
23+
* two paths are guarded independently.
1724
*
1825
* Requires `pnpm build` first.
1926
*/
2027
import { execFileSync } from 'node:child_process';
21-
import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
28+
import {
29+
existsSync,
30+
mkdirSync,
31+
readFileSync,
32+
readdirSync,
33+
rmSync,
34+
statSync,
35+
writeFileSync,
36+
} from 'node:fs';
2237
import { createRequire } from 'node:module';
2338
import { dirname, join, resolve } from 'node:path';
2439
import { fileURLToPath } from 'node:url';
@@ -27,7 +42,6 @@ import { parseArgs } from 'node:util';
2742
const require = createRequire(import.meta.url);
2843
const pkgRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');
2944
const workDir = join(pkgRoot, '.type-perf');
30-
const budgetFile = join(pkgRoot, 'type-perf.budget.json');
3145

3246
// parseArgs over hand-rolled indexOf: it accepts `--count=500` as well as
3347
// `--count 500`, and throws on an unknown flag or a valueless one instead of
@@ -36,7 +50,11 @@ const budgetFile = join(pkgRoot, 'type-perf.budget.json');
3650
let parsed;
3751
try {
3852
parsed = parseArgs({
39-
options: { count: { type: 'string', default: '100' }, update: { type: 'boolean' } },
53+
options: {
54+
augment: { type: 'boolean' },
55+
count: { type: 'string', default: '100' },
56+
update: { type: 'boolean' },
57+
},
4058
strict: true,
4159
});
4260
} catch (error) {
@@ -45,12 +63,21 @@ try {
4563
}
4664

4765
const update = parsed.values.update === true;
66+
const augment = parsed.values.augment === true;
4867
const count = Number(parsed.values.count);
4968
if (!Number.isInteger(count) || count < 1) {
5069
console.error(`type-perf: --count needs a positive integer, got ${parsed.values.count}`);
5170
process.exit(1);
5271
}
5372

73+
// The augmented and default paths have different costs and different baselines,
74+
// so they keep separate budget files; one run never clobbers the other.
75+
const budgetFile = join(
76+
pkgRoot,
77+
augment ? 'type-perf.augment.budget.json' : 'type-perf.budget.json'
78+
);
79+
const updateHint = augment ? '--augment --update' : '--update';
80+
5481
const distEntry = join(pkgRoot, 'dist', 'index.d.ts');
5582
if (!existsSync(distEntry)) {
5683
console.error('type-perf: dist/index.d.ts missing -- run `pnpm build` first.');
@@ -63,7 +90,10 @@ if (!existsSync(distEntry)) {
6390
// `test/` never reaches dist, and `utils/errors.ts` is generated -- the test run
6491
// rewrites it, so counting either would report a stale dist after every
6592
// `pnpm test` and train everyone to ignore the warning.
66-
const IGNORED_SOURCES = new Set([join(pkgRoot, 'src', 'test'), join(pkgRoot, 'src', 'utils', 'errors.ts')]);
93+
const IGNORED_SOURCES = new Set([
94+
join(pkgRoot, 'src', 'test'),
95+
join(pkgRoot, 'src', 'utils', 'errors.ts'),
96+
]);
6797

6898
const newestSource = (function newest(dir) {
6999
let latest = 0;
@@ -387,6 +417,18 @@ export const CanaryNative = <NativeCanary notAPropOfView={1} />;
387417
export const NativeOk = <NativeCanary testID="ok" />;
388418
`;
389419

420+
// The `data-*` template-literal augmentation from #5796. A separate module (an
421+
// `import` makes it one) so the `declare module` merges into every fixture file
422+
// without editing the shared HEADER. Only written under `--augment`.
423+
const AUGMENT = `import 'react';
424+
425+
declare module 'react' {
426+
interface HTMLAttributes<T> {
427+
[dataAttribute: \`data-\${string}\`]: string | undefined;
428+
}
429+
}
430+
`;
431+
390432
rmSync(workDir, { recursive: true, force: true });
391433
mkdirSync(join(workDir, 'src'), { recursive: true });
392434

@@ -396,6 +438,7 @@ for (let start = 0, f = 0; start < count; start += PER_FILE, f++) {
396438
writeFileSync(join(workDir, 'src', `mod${f}.tsx`), `${HEADER}\n${body.join('\n')}`);
397439
}
398440
writeFileSync(join(workDir, 'src', 'canary.tsx'), CANARY);
441+
if (augment) writeFileSync(join(workDir, 'src', '_augment.d.ts'), AUGMENT);
399442

400443
writeFileSync(
401444
join(workDir, 'tsconfig.json'),
@@ -484,7 +527,10 @@ const versions = {
484527
typesReact: require('@types/react/package.json').version,
485528
};
486529

487-
console.log(`type-perf: ${count} components, TypeScript ${versions.typescript}, @types/react ${versions.typesReact}`);
530+
console.log(
531+
`type-perf${augment ? ' (augmented)' : ''}: ${count} components, ` +
532+
`TypeScript ${versions.typescript}, @types/react ${versions.typesReact}`
533+
);
488534
console.log(` types: ${measured.types.toLocaleString()}`);
489535
console.log(` instantiations: ${measured.instantiations.toLocaleString()}`);
490536
console.log(` memory: ${Math.round(measured.memoryKb / 1024).toLocaleString()} MB`);
@@ -505,9 +551,14 @@ if (update) {
505551
process.exit(0);
506552
}
507553

554+
if (!existsSync(budgetFile)) {
555+
console.error(`type-perf: ${budgetFile} does not exist -- run with ${updateHint} to create it.`);
556+
process.exit(1);
557+
}
558+
508559
const budget = JSON.parse(readFileSync(budgetFile, 'utf8'));
509560
if (!budget.measured || !budget.tolerancePct) {
510-
console.error(`type-perf: ${budgetFile} is not in the expected shape -- run with --update.`);
561+
console.error(`type-perf: ${budgetFile} is not in the expected shape -- run with ${updateHint}.`);
511562
process.exit(1);
512563
}
513564

@@ -517,7 +568,9 @@ if (!budget.measured || !budget.tolerancePct) {
517568
// to enforce. Any budget written before a metric existed has exactly this shape.
518569
for (const metric of Object.keys(TOLERANCE_PCT)) {
519570
if (!Number.isFinite(budget.measured[metric]) || !Number.isFinite(budget.tolerancePct[metric])) {
520-
console.error(`type-perf: budget is missing '${metric}' -- run with --update to re-measure.`);
571+
console.error(
572+
`type-perf: budget is missing '${metric}' -- run with ${updateHint} to re-measure.`
573+
);
521574
process.exit(1);
522575
}
523576
}
@@ -558,15 +611,15 @@ if (over.length > 0) {
558611
}
559612
console.error(
560613
'Consumer type-check cost grew. Find the cause before raising the budget; ' +
561-
'run with --update only when the increase is understood and intended.'
614+
`run with ${updateHint} only when the increase is understood and intended.`
562615
);
563616
process.exit(1);
564617
}
565618

566619
for (const [label, actual, baseline] of under) {
567620
console.log(
568621
`type-perf: ${label} improved ${Math.round((1 - actual / baseline) * 100)}% ` +
569-
`(${baseline.toLocaleString()} -> ${actual.toLocaleString()}); run --update to bank it`
622+
`(${baseline.toLocaleString()} -> ${actual.toLocaleString()}); run ${updateHint} to bank it`
570623
);
571624
}
572625

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

Lines changed: 38 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,36 @@ export type TargetProps<R extends Runtime, T> = T extends keyof React.JSX.Intrin
215215
? ComponentTargetProps<R, T>
216216
: {};
217217

218+
/**
219+
* True when an application has augmented `React.HTMLAttributes` with a `data-*`
220+
* template-literal index signature, the common pattern for allowing arbitrary
221+
* data attributes. Detected by testing whether {@link DataAttributes}' key is
222+
* already a key of a stock intrinsic element.
223+
*
224+
* Scope is exactly `data-${string}`: an `aria-${string}` or other custom-prefix
225+
* template augmentation is not detected and still hits the {@link WithCSSVars}
226+
* path (#5796). `data-*` is the dominant augmentation, so the narrow probe buys
227+
* the common case; widening it means OR-ing another literal prefix in here.
228+
*/
229+
type IntrinsicElementsHaveDataIndex =
230+
keyof DataAttributes extends keyof React.JSX.IntrinsicElements['div'] ? true : false;
231+
232+
/**
233+
* {@link WithCSSVars} for the augmented intrinsic path. Identical widening, but
234+
* filters `style` with {@link FastOmit}'s mapped-type `as` clause instead of the
235+
* built-in `Omit`. `Omit<P, 'style'>` is `Pick<P, Exclude<keyof P, 'style'>>`,
236+
* and distributing that `Exclude` over a template-literal key across every
237+
* intrinsic element exceeds TypeScript's union complexity limit (#5796);
238+
* `FastOmit` drops the key without the distribution.
239+
*
240+
* Kept off the normal path: `FastOmit` costs materially more instantiations at
241+
* that scale, and the union `style` member (mirroring {@link WithCSSVars}) is
242+
* what preserves the declaration-site relation a plain intersection regresses.
243+
*/
244+
type WithCSSVarsForDataIndex<P extends BaseObject> = FastOmit<P, 'style'> & {
245+
style?: CSSPropertiesWithVars | (P[keyof P & 'style'] & {}) | undefined;
246+
};
247+
218248
/**
219249
* Props of an HTML or SVG tag.
220250
*
@@ -223,12 +253,15 @@ export type TargetProps<R extends Runtime, T> = T extends keyof React.JSX.Intrin
223253
* instead of the full expansion of every tag attribute. See {@link WithCSSVars}
224254
* for why a conditional's inline branch cannot keep a name.
225255
*
226-
* Applies the widening directly rather than through {@link OverrideStyle}: every
227-
* intrinsic element declares `style`, so the guard has nothing to decide here.
256+
* Applies {@link WithCSSVars} directly except under a `data-*` augmentation,
257+
* where {@link WithCSSVarsForDataIndex} avoids the `Omit` that would blow the
258+
* union complexity limit. The probe is a global constant, so the common path is
259+
* untouched.
228260
*/
229-
type IntrinsicProps<T extends keyof React.JSX.IntrinsicElements> = WithCSSVars<
230-
React.JSX.IntrinsicElements[T]
231-
>;
261+
type IntrinsicProps<T extends keyof React.JSX.IntrinsicElements> =
262+
IntrinsicElementsHaveDataIndex extends true
263+
? WithCSSVarsForDataIndex<React.JSX.IntrinsicElements[T]>
264+
: WithCSSVars<React.JSX.IntrinsicElements[T]>;
232265

233266
/**
234267
* Props of a component render target. Named for the same reason as {@link IntrinsicProps}.
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import React from 'react';
2+
import styled, { IStyledComponent } from '../src';
3+
import { FastOmit } from '../src/types';
4+
5+
declare module 'react' {
6+
interface HTMLAttributes<T> {
7+
[dataAttribute: `data-${string}`]: string | undefined;
8+
}
9+
}
10+
11+
const Example = styled.div``;
12+
13+
<Example data-role="test" style={{ '--accent': 'tomato' }} />;
14+
15+
// @ts-expect-error data attribute values retain the augmented string type
16+
const invalidAttrs: React.HTMLAttributes<HTMLDivElement> = { 'data-role': 42 };
17+
18+
/**
19+
* Conditionally selecting between two styled components produced TS2590 at the
20+
* JSX call site even with `skipLibCheck` on (#5796): the union of the two
21+
* component types re-ran the widening the declaration escaped. Rendering the
22+
* picked component must type-check.
23+
*/
24+
const Tiny = styled.div``;
25+
const Wide = styled.div``;
26+
27+
const Conditional = ({ tiny }: { tiny: boolean }) => {
28+
const Wrapper = tiny ? Tiny : Wide;
29+
return <Wrapper data-role="conditional" style={{ '--accent': 'tomato' }} />;
30+
};
31+
32+
<Conditional tiny />;
33+
34+
/**
35+
* The augmented intrinsic widening must keep an explicit declaration-site
36+
* annotation relatable. An intersection that requires the custom-property index
37+
* on `style` breaks assignment from a `styled.div` whose annotated bag carries
38+
* plain `CSSProperties`; the union widening preserves it (#5796).
39+
*/
40+
type DivProps = React.JSX.IntrinsicElements['div'];
41+
42+
const Annotated: IStyledComponent<'web', FastOmit<DivProps, never> & { $a?: number }> = styled.div<{
43+
$a?: number;
44+
}>``;
45+
46+
void Annotated;
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
{
2+
"extends": "./tsconfig.json",
3+
"compilerOptions": {
4+
"incremental": false,
5+
"noUnusedLocals": false,
6+
"skipLibCheck": true
7+
},
8+
"include": ["test-types/template-index-signature.tsx"]
9+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
{
2+
"count": 100,
3+
"measured": {
4+
"instantiations": 965491,
5+
"memoryKb": 206495,
6+
"types": 39584
7+
},
8+
"tolerancePct": {
9+
"instantiations": 10,
10+
"memoryKb": 12,
11+
"types": 10
12+
},
13+
"versions": {
14+
"typescript": "5.9.3",
15+
"typesReact": "18.3.28"
16+
}
17+
}

0 commit comments

Comments
 (0)