Skip to content

Commit 1888c73

Browse files
quantizorclaude
andcommitted
fix: improve withTheme HOC type safety and eliminate double type cast
Co-Authored-By: Claude Opus 4.6 <[email protected]>
1 parent dbe0aae commit 1888c73

2 files changed

Lines changed: 28 additions & 19 deletions

File tree

‎.changeset/fix-withtheme-types.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 `withTheme` HOC types: ref now correctly resolves to the component instance type instead of the constructor, and `theme` is properly optional in the wrapped component's props.

‎packages/styled-components/src/hoc/withTheme.tsx‎

Lines changed: 23 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -6,32 +6,36 @@ import determineTheme from '../utils/determineTheme';
66
import getComponentName from '../utils/getComponentName';
77
import hoist, { NonReactStatics } from '../utils/hoist';
88

9+
type WithThemeOuterProps<T extends AnyComponent> = Omit<
10+
React.ComponentPropsWithRef<T>,
11+
keyof ExecutionProps
12+
> &
13+
ExecutionProps;
14+
915
export default function withTheme<T extends AnyComponent>(
1016
Component: T
1117
): React.ForwardRefExoticComponent<
12-
React.PropsWithoutRef<React.ComponentPropsWithRef<T> & ExecutionProps> & React.RefAttributes<T>
18+
React.PropsWithoutRef<WithThemeOuterProps<T>> & React.RefAttributes<any>
1319
> &
1420
NonReactStatics<T> {
15-
const WithTheme = React.forwardRef<T, React.ComponentPropsWithRef<T> & ExecutionProps>(
16-
(props, ref) => {
17-
const theme = !IS_RSC ? React.useContext(ThemeContext) : undefined;
18-
const themeProp = determineTheme(props, theme, Component.defaultProps);
21+
const WithTheme = React.forwardRef<any, WithThemeOuterProps<T>>((props, ref) => {
22+
const theme = !IS_RSC ? React.useContext(ThemeContext) : undefined;
23+
const themeProp = determineTheme(props, theme, Component.defaultProps);
1924

20-
if (process.env.NODE_ENV !== 'production' && themeProp === undefined) {
21-
console.warn(
22-
`[withTheme] You are not using a ThemeProvider nor passing a theme prop or a theme in defaultProps in component class "${getComponentName(
23-
Component
24-
)}"`
25-
);
26-
}
27-
28-
return React.createElement(Component, {
29-
...props,
30-
theme: themeProp,
31-
ref,
32-
} as React.ComponentPropsWithRef<T>);
25+
if (process.env.NODE_ENV !== 'production' && themeProp === undefined) {
26+
console.warn(
27+
`[withTheme] You are not using a ThemeProvider nor passing a theme prop or a theme in defaultProps in component class "${getComponentName(
28+
Component
29+
)}"`
30+
);
3331
}
34-
);
32+
33+
return React.createElement(Component, {
34+
...props,
35+
theme: themeProp,
36+
ref,
37+
} as React.ComponentPropsWithRef<T>);
38+
});
3539

3640
WithTheme.displayName = `WithTheme(${getComponentName(Component)})`;
3741

0 commit comments

Comments
 (0)