Skip to content

Commit 7ce6aea

Browse files
authored
feat(types): add StyledComponent for explicit export annotations (#5799)
* feat(types): add StyledComponent for explicit export annotations Packages that emit their own declarations, including any project using isolatedDeclarations, must annotate every exported styled component, and there was no public type for it: consumers reached into styled-components/dist/types or hand-assembled a shape that silently dropped members such as hoisted statics. StyledComponent<Target, Props> is now exported from the web and native entries. It resolves to the exact type styled(Target)<Props> produces across every target kind, .withConfig, and hoisted statics, so the annotation is not lossy and the check against the inferred component stays cheap. Contract tests enumerate the target-kind matrix and the two .attrs() spelling rules; three annotated-public type-perf fixture kinds guard the alias's construction arms (intrinsic tag, statics wrap, factory widening) with both budgets re-measured. * docs(type-perf): document the annotatedPublic fixture kinds The type-performance guide enumerates the fixture kinds; add the three annotatedPublic* kinds introduced alongside StyledComponent so the enumeration matches the fixture. * docs(types): trim StyledComponent doc prose
1 parent 1593023 commit 7ce6aea

10 files changed

Lines changed: 270 additions & 8 deletions

File tree

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
---
2+
"styled-components": minor
3+
---
4+
5+
Added a `StyledComponent<Target, Props>` type for annotating explicitly-typed styled component exports.
6+
7+
Packages that emit their own declaration files, including any project using `isolatedDeclarations`, must annotate every exported styled component, and there was no public type for it: consumers reached into internal paths or hand-assembled one that dropped members like a wrapped component's hoisted statics.
8+
9+
`StyledComponent` is exported from the web and native entries. Name the target and props as you passed them to `styled`:
10+
11+
```tsx
12+
import styled, { type StyledComponent } from 'styled-components';
13+
14+
export const Card: StyledComponent<'div', { $active?: boolean }> = styled.div<{ $active?: boolean }>`...`;
15+
export const CloseButton: StyledComponent<typeof IconButton> = styled(IconButton)`...`;
16+
```
17+
18+
It resolves to the exact type `styled(Target)<Props>` produces, so the annotation is not lossy.

‎docs/type-performance.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,13 @@ bag is hand-written instead of the shape the library computes. This is what isol
4747
that deepened that relation would move nothing here. Like `unionTarget` it is expensive per component,
4848
so it too moved the recorded budget on its own -- fixture growth, not a regression.
4949

50+
Three `annotatedPublic*` kinds price the same declaration site with the public `StyledComponent<Target,
51+
Props>` alias in place of the hand-written bag. They cover its distinct construction arms so a change to
52+
`StyledComponent`, `MergeProps`, `TargetProps`, or `WidenForUntypedTarget` that reintroduced a divergent
53+
bag would regress them: `annotatedPublic` an intrinsic tag, `annotatedPublicWrap` the hoisted-statics
54+
intersection, `annotatedPublicFactory` the `WidenForUntypedTarget` arm. Each is expensive per component,
55+
so each moved the budget on its own -- fixture growth, not a regression.
56+
5057
Four exotic kinds each price a `types.ts` conditional arm no other kind reaches, and each also fails the
5158
clean-compile gate if its mechanism regresses, so they are correctness canaries sitting inside the perf
5259
gate the way `unionTarget` is: `permissiveFactory` (a Mantine-style un-introspectable target, the

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

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,14 @@ const AS_TAGS = ['a', 'button', 'label', 'section', 'video', 'ul'];
134134
// deepened that relation would be invisible. Like `unionTarget`, it is expensive
135135
// per component, so adding it moved the recorded budget on its own -- that jump
136136
// is fixture growth, not a regression.
137+
// `annotatedPublic*` price the same declaration site with the public
138+
// `StyledComponent<Target, Props>` alias instead of a hand-assembled bag. The three
139+
// cover its distinct construction arms so a change to `StyledComponent`,
140+
// `MergeProps`, `TargetProps`, or `WidenForUntypedTarget` that reintroduced a
141+
// divergent bag regresses them: `annotatedPublic` an intrinsic tag,
142+
// `annotatedPublicWrap` the hoisted-statics intersection, `annotatedPublicFactory`
143+
// the `WidenForUntypedTarget` arm. Expensive per component, so each moved the budget
144+
// on its own -- fixture growth, not a regression.
137145
// The four exotic kinds below each price a `types.ts` conditional arm no other
138146
// kind reaches, and each doubles as a correctness canary (the run fails on any
139147
// fixture compile error): `permissiveFactory` the un-introspectable
@@ -151,6 +159,9 @@ const KIND_WEIGHTS = [
151159
['chained', 3],
152160
['attrsTag', 2],
153161
['annotated', 1],
162+
['annotatedPublic', 1],
163+
['annotatedPublicWrap', 1],
164+
['annotatedPublicFactory', 1],
154165
['attrsWrap', 1],
155166
['genericWrapper', 1],
156167
['unionTarget', 1],
@@ -171,7 +182,7 @@ function kindOf(i) {
171182
}
172183

173184
const HEADER = `import * as React from 'react';
174-
import styled, { type FastOmit, type IStyledComponent } from 'styled-components';
185+
import styled, { type FastOmit, type IStyledComponent, type StyledComponent } from 'styled-components';
175186
176187
type DivProps = React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>;
177188
@@ -270,6 +281,24 @@ function unit(i) {
270281
// & string`, the public spelling of the type the report annotates against.
271282
decl = `const ${N}: IStyledComponent<'web', FastOmit<DivProps, never> & { $a${i}?: number }> = styled.div<{ $a${i}?: number }>\`
272283
color: \${p => (p.$a${i} ? 'red' : 'blue')};
284+
\`;`;
285+
break;
286+
case 'annotatedPublic':
287+
// Public annotation on an intrinsic tag (see KIND_WEIGHTS).
288+
decl = `const ${N}: StyledComponent<'div', { $a${i}?: number }> = styled.div<{ $a${i}?: number }>\`
289+
color: \${p => (p.$a${i} ? 'red' : 'blue')};
290+
\`;`;
291+
break;
292+
case 'annotatedPublicWrap':
293+
// Public annotation on a wrapped component: the hoisted-statics arm.
294+
decl = `const ${N}: StyledComponent<typeof Plain, { $a${i}?: number }> = styled(Plain)<{ $a${i}?: number }>\`
295+
margin: \${p => p.$a${i} ?? 0}px;
296+
\`;`;
297+
break;
298+
case 'annotatedPublicFactory':
299+
// Public annotation on an un-introspectable target: the widening arm.
300+
decl = `const ${N}: StyledComponent<typeof Factory> = styled(Factory)\`
301+
color: ${i % 2 ? 'red' : 'blue'};
273302
\`;`;
274303
break;
275304
case 'attrsWrap':

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ export {
2222
PolymorphicComponentProps,
2323
RuleSet,
2424
Runtime,
25+
StyledComponent,
2526
StyledObject,
2627
StyledOptions,
2728
StyleFunction,

‎packages/styled-components/src/native/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,7 @@ export {
108108
IStyledComponent,
109109
IStyledComponentFactory,
110110
IStyledStatics,
111+
NativeStyledComponent as StyledComponent,
111112
NativeTarget,
112113
PolymorphicComponent,
113114
PolymorphicComponentProps,

‎packages/styled-components/src/test/types.native.tsx‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ import React, { useRef } from 'react';
3131
import { Text, TextInput, View } from 'react-native';
3232
import type { PropsWithChildren } from 'react';
3333
import type { TextProps as RNTextProps, ViewProps as RNViewProps } from 'react-native';
34-
import styled, { DefaultTheme } from '../native';
34+
import styled, { DefaultTheme, StyledComponent } from '../native';
3535

3636
/**
3737
* Augment DefaultTheme so tests can reference theme properties. This is the
@@ -363,3 +363,25 @@ const extractedNumberOfLines: ExtractedTextProps['numberOfLines'] = 3;
363363
void extractedNumberOfLines;
364364
const extractedTargetProps: RNTextProps['ellipsizeMode'] = 'tail';
365365
void extractedTargetProps;
366+
367+
/* ------------------------------------------------------------------------- *
368+
* `StyledComponent<Target, Props>` from the native entry, proven exact the same
369+
* way as web (assign both directions). Native carries no hoisted-statics
370+
* intersection, so a target-wrap case exercises that difference.
371+
* ------------------------------------------------------------------------- */
372+
const _scNativeTag = styled.View<{ $active?: boolean }>``;
373+
const _scNativeTagAnnotated: StyledComponent<typeof View, { $active?: boolean }> = _scNativeTag;
374+
const _scNativeTagBack: typeof _scNativeTag = _scNativeTagAnnotated;
375+
void _scNativeTagBack;
376+
377+
const _scNativeWrap = styled(TextInput)``;
378+
const _scNativeWrapAnnotated: StyledComponent<typeof TextInput> = _scNativeWrap;
379+
const _scNativeWrapBack: typeof _scNativeWrap = _scNativeWrapAnnotated;
380+
void _scNativeWrapBack;
381+
382+
// `.attrs()` follows the same rules as web: an already-optional backfilled prop
383+
// leaves the type unchanged.
384+
const _scNativeAttrs = styled.TextInput.attrs({ editable: true })<{ $x?: number }>``;
385+
const _scNativeAttrsAnnotated: StyledComponent<typeof TextInput, { $x?: number }> = _scNativeAttrs;
386+
const _scNativeAttrsBack: typeof _scNativeAttrs = _scNativeAttrsAnnotated;
387+
void _scNativeAttrsBack;

‎packages/styled-components/src/test/types.tsx‎

Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
Interpolation,
1212
IStyledComponent,
1313
RuleSet,
14+
StyledComponent,
1415
StyledObject,
1516
WebTarget,
1617
withTheme,
@@ -627,6 +628,140 @@ const StyledNoStyleTarget = styled(NoStyleTarget)``;
627628
/** `style={undefined}` stays assignable under exactOptionalPropertyTypes. */
628629
<DivWithCSSVariable style={undefined} />;
629630

631+
/**
632+
* Contract for the public `StyledComponent<Target, Props>` annotation: it must
633+
* resolve to the exact type `styled(Target)<Props>` produces for every target kind
634+
* and construction form. `_scExact` compiles only when the two types are mutually
635+
* assignable; `Props` is invariant, so that is an identity check, not one-way
636+
* compatibility. The `.attrs()` rules the cases enumerate are documented in
637+
* `types.ts`.
638+
*/
639+
type _ScExact<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false;
640+
const _scExact = <_T extends true>(): void => {};
641+
642+
/* Headline forms: explicit annotation, both assignment directions. */
643+
const _scPlain = styled.div<{ $active?: boolean }>``;
644+
const _scPlainAnnotated: StyledComponent<'div', { $active?: boolean }> = _scPlain;
645+
const _scPlainBack: typeof _scPlain = _scPlainAnnotated;
646+
void _scPlainBack;
647+
648+
/** Wrapping a component: hoisted target statics survive into the annotation. */
649+
function IconButtonBase(props: { label: string; className?: string }) {
650+
return <button className={props.className}>{props.label}</button>;
651+
}
652+
IconButtonBase.displayName = 'IconButton';
653+
const _scWrap = styled(IconButtonBase)``;
654+
const _scWrapAnnotated: StyledComponent<typeof IconButtonBase> = _scWrap;
655+
const _scWrapBack: typeof _scWrap = _scWrapAnnotated;
656+
void _scWrapBack;
657+
658+
const _scWrapProps = styled(IconButtonBase)<{ $tone?: 'a' | 'b' }>``;
659+
const _scWrapPropsAnnotated: StyledComponent<typeof IconButtonBase, { $tone?: 'a' | 'b' }> =
660+
_scWrapProps;
661+
const _scWrapPropsBack: typeof _scWrapProps = _scWrapPropsAnnotated;
662+
void _scWrapPropsBack;
663+
664+
/* Breadth: every distinct target kind resolves exactly. */
665+
const _scCustomEl = styled('my-element')``;
666+
_scExact<_ScExact<typeof _scCustomEl, StyledComponent<'my-element'>>>();
667+
668+
class _ScCls extends React.Component<{ label: string; className?: string }> {
669+
render() {
670+
return <div className={this.props.className}>{this.props.label}</div>;
671+
}
672+
}
673+
const _scClass = styled(_ScCls)``;
674+
_scExact<_ScExact<typeof _scClass, StyledComponent<typeof _ScCls>>>();
675+
676+
const _ScFwd = React.forwardRef<HTMLDivElement, { label: string }>((p, ref) => (
677+
<div ref={ref}>{p.label}</div>
678+
));
679+
const _scFwd = styled(_ScFwd)``;
680+
_scExact<_ScExact<typeof _scFwd, StyledComponent<typeof _ScFwd>>>();
681+
682+
const _ScMemo = React.memo(IconButtonBase);
683+
const _scMemo = styled(_ScMemo)``;
684+
_scExact<_ScExact<typeof _scMemo, StyledComponent<typeof _ScMemo>>>();
685+
686+
/** styled-of-styled: the wrapped styled component's statics chain through. */
687+
const _ScBase = styled.button<{ $v?: number }>``;
688+
const _scOfStyled = styled(_ScBase)<{ $w?: string }>``;
689+
_scExact<_ScExact<typeof _scOfStyled, StyledComponent<typeof _ScBase, { $w?: string }>>>();
690+
691+
/** union-props target (#5787). */
692+
const _ScPressable = (
693+
_p: React.ButtonHTMLAttributes<HTMLButtonElement> | React.AnchorHTMLAttributes<HTMLAnchorElement>
694+
) => null;
695+
const _scUnion = styled(_ScPressable)<{ $x?: number }>``;
696+
_scExact<_ScExact<typeof _scUnion, StyledComponent<typeof _ScPressable, { $x?: number }>>>();
697+
698+
/** generic polymorphic target (#5756). */
699+
type _ScPolyProps<C extends React.ElementType, P = object> = React.PropsWithChildren<
700+
P & { as?: C }
701+
> &
702+
Omit<React.ComponentPropsWithoutRef<C>, keyof (P & { as?: C })>;
703+
const _ScPoly = <C extends React.ElementType = 'button'>(
704+
_p: _ScPolyProps<C, { variant?: 'primary' | 'secondary' }>
705+
) => null;
706+
const _scPoly = styled(_ScPoly)<{ $x?: number }>``;
707+
_scExact<_ScExact<typeof _scPoly, StyledComponent<typeof _ScPoly, { $x?: number }>>>();
708+
709+
/** disjoint-union target (#5787 sibling). */
710+
const _ScDisjoint = (_p: { onlyA: string } | { onlyB: number }) => null;
711+
const _scDisjoint = styled(_ScDisjoint)``;
712+
_scExact<_ScExact<typeof _scDisjoint, StyledComponent<typeof _ScDisjoint>>>();
713+
714+
/** `.withConfig()` leaves the type unchanged. */
715+
const _scWithConfig = styled.div.withConfig({ displayName: 'X' })<{ $x?: number }>``;
716+
_scExact<_ScExact<typeof _scWithConfig, StyledComponent<'div', { $x?: number }>>>();
717+
718+
/**
719+
* Un-introspectable factory target (Mantine v7 shape): the annotation carries the
720+
* same permissive widening the constructor applies, through `WidenForUntypedTarget`.
721+
*/
722+
type SCFactoryProps<C, P = {}> = C extends React.ElementType
723+
? Omit<React.ComponentProps<C>, keyof P> & P & { component?: C } & { ref?: any }
724+
: P & { component: React.ElementType };
725+
type SCFactory = (<C = 'button'>(
726+
p: SCFactoryProps<C, { children?: React.ReactNode }>
727+
) => React.ReactElement) &
728+
Omit<React.FunctionComponent<SCFactoryProps<any, { children?: React.ReactNode }>>, never> & {
729+
extend: (p: any) => any;
730+
};
731+
declare const scFactory: SCFactory;
732+
const _scFactory = styled(scFactory)``;
733+
const _scFactoryAnnotated: StyledComponent<typeof scFactory> = _scFactory;
734+
const _scFactoryBack: typeof _scFactory = _scFactoryAnnotated;
735+
void _scFactoryBack;
736+
737+
/**
738+
* `.attrs()` rules (backfilled keys and target redirect are not in
739+
* `<Target, Props>`): a backfilled required prop becomes optional in `Props`; an
740+
* object-form `as` redirect adds the resolved target's props to `Props`. Attrs
741+
* over already-optional props (the common case) needs neither.
742+
*/
743+
const _scAttrsPlain = styled.input.attrs({ type: 'text' })<{ $x?: number }>``;
744+
_scExact<_ScExact<typeof _scAttrsPlain, StyledComponent<'input', { $x?: number }>>>();
745+
746+
const _scAttrsBackfill = styled(IconButtonBase).attrs({ label: 'x' })``;
747+
_scExact<
748+
_ScExact<typeof _scAttrsBackfill, StyledComponent<typeof IconButtonBase, { label?: string }>>
749+
>();
750+
751+
const _scAttrsRedirect = styled.button.attrs({ as: 'a' })``;
752+
_scExact<
753+
_ScExact<typeof _scAttrsRedirect, StyledComponent<'button', React.ComponentPropsWithRef<'a'>>>
754+
>();
755+
756+
/**
757+
* A genuinely different required prop is rejected, never silently accepted or
758+
* dropped. (Optional-only or structurally-equal mismatches stay assignable, per
759+
* TS structural typing, and are harmless: equal shapes behave identically.)
760+
*/
761+
// @ts-expect-error the real required prop is $y; annotating a required $x is rejected
762+
const _scWrongReq: StyledComponent<'div', { $x: number }> = styled.div<{ $y: number }>``;
763+
void _scWrongReq;
764+
630765
/** Widening is visible through prop extraction, not only at the call site. */
631766
const StyleExtractionTarget = styled.div``;
632767
const extractedStyle: React.ComponentProps<typeof StyleExtractionTarget>['style'] = {

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

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -435,6 +435,55 @@ export type IStyledComponent<
435435
Props extends BaseObject = BaseObject,
436436
> = IStyledComponentBase<R, Props> & string;
437437

438+
/**
439+
* The type of a web styled component, for annotating an explicit export.
440+
* `isolatedDeclarations` and `.d.ts`-emitting packages require one; inference does
441+
* not survive declaration emit. Name the target and props as you passed them to
442+
* `styled`:
443+
*
444+
* ```ts
445+
* export const Card: StyledComponent<'div', { $active?: boolean }> = styled.div<{ $active?: boolean }>`…`;
446+
* export const CloseButton: StyledComponent<typeof IconButton> = styled(IconButton)`…`;
447+
* ```
448+
*
449+
* Resolves to the exact type `styled(Target)<Props>` produces for every target kind
450+
* and `.withConfig(…)`, hoisted statics included.
451+
*
452+
* `.attrs(…)` needs two adjustments, since its backfilled keys and target redirect
453+
* are not in `<Target, Props>`:
454+
* - A backfilled required prop becomes optional: declare it optional in `Props`.
455+
* - An object-form `as` redirect (`.attrs({ as: 'a' })`) keeps the base props and
456+
* adds the resolved target's: pass those as `Props`
457+
* (`StyledComponent<'button', React.ComponentPropsWithRef<'a'>>`), or redirect
458+
* with the `as` prop at the call site.
459+
*
460+
* Web only; the native entry exports a native `StyledComponent`.
461+
*/
462+
export type StyledComponent<
463+
Target extends WebTarget,
464+
Props extends BaseObject = BaseObject,
465+
> = IStyledComponent<
466+
'web',
467+
WidenForUntypedTarget<TargetProps<'web', Target>, MergeProps<TargetProps<'web', Target>, Props>>
468+
> &
469+
(Target extends string ? {} : Omit<Target, keyof React.Component<any>>);
470+
471+
/**
472+
* The React Native counterpart to {@link StyledComponent}, re-exported as
473+
* `StyledComponent` from `styled-components/native`. No hoisted-statics
474+
* intersection: the constructor's statics widening is web-only.
475+
*/
476+
export type NativeStyledComponent<
477+
Target extends NativeTarget,
478+
Props extends BaseObject = BaseObject,
479+
> = IStyledComponent<
480+
'native',
481+
WidenForUntypedTarget<
482+
TargetProps<'native', Target>,
483+
MergeProps<TargetProps<'native', Target>, Props>
484+
>
485+
>;
486+
438487
// corresponds to createStyledComponent
439488
export interface IStyledComponentFactory<
440489
out R extends Runtime,

‎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": 965491,
5-
"memoryKb": 206495,
6-
"types": 39584
4+
"instantiations": 895632,
5+
"memoryKb": 201742,
6+
"types": 38232
77
},
88
"tolerancePct": {
99
"instantiations": 10,

‎packages/styled-components/type-perf.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": 888000,
5-
"memoryKb": 205788,
6-
"types": 39346
4+
"instantiations": 820402,
5+
"memoryKb": 201312,
6+
"types": 38055
77
},
88
"tolerancePct": {
99
"instantiations": 10,

0 commit comments

Comments
 (0)