Skip to content

Commit 4d3b60d

Browse files
Added basic TS type support for as prop on styled components (#1874)
* Add type for as prop * Add changeset * Simplify type for `as` prop * Tweak changeset Co-authored-by: Mateusz Burzyński <[email protected]>
1 parent 6d32d82 commit 4d3b60d

File tree

3 files changed

+31
-4
lines changed

3 files changed

+31
-4
lines changed

.changeset/cyan-jobs-carry.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@emotion/styled': minor
3+
---
4+
5+
Added basic TS type support for `as` prop on styled components. It's possible to pass any component to it but it has no effect on other accepted props. This means that it's not 100% type-safe so use it sparingly and with care.

packages/styled/types/base.d.ts

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -106,12 +106,22 @@ export interface CreateStyled {
106106
>(
107107
component: C,
108108
options: FilteringStyledOptions<PropsOf<C>, ForwardedProps>
109-
): CreateStyledComponent<Pick<PropsOf<C>, ForwardedProps> & { theme?: Theme }>
109+
): CreateStyledComponent<
110+
Pick<PropsOf<C>, ForwardedProps> & {
111+
theme?: Theme
112+
as?: React.ElementType
113+
}
114+
>
110115

111116
<C extends React.ComponentType<React.ComponentProps<C>>>(
112117
component: C,
113118
options?: StyledOptions<PropsOf<C>>
114-
): CreateStyledComponent<PropsOf<C> & { theme?: Theme }>
119+
): CreateStyledComponent<
120+
PropsOf<C> & {
121+
theme?: Theme
122+
as?: React.ElementType
123+
}
124+
>
115125

116126
<
117127
Tag extends keyof JSX.IntrinsicElements,
@@ -120,14 +130,17 @@ export interface CreateStyled {
120130
tag: Tag,
121131
options: FilteringStyledOptions<JSX.IntrinsicElements[Tag], ForwardedProps>
122132
): CreateStyledComponent<
123-
{ theme?: Theme },
133+
{ theme?: Theme; as?: React.ElementType },
124134
Pick<JSX.IntrinsicElements[Tag], ForwardedProps>
125135
>
126136

127137
<Tag extends keyof JSX.IntrinsicElements>(
128138
tag: Tag,
129139
options?: StyledOptions<JSX.IntrinsicElements[Tag]>
130-
): CreateStyledComponent<{ theme?: Theme }, JSX.IntrinsicElements[Tag]>
140+
): CreateStyledComponent<
141+
{ theme?: Theme; as?: React.ElementType },
142+
JSX.IntrinsicElements[Tag]
143+
>
131144
}
132145

133146
declare const styled: CreateStyled

packages/styled/types/tests-base.tsx

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -423,3 +423,12 @@ const StyledButton = StyledDiv.withComponent('button')
423423
e
424424
}}
425425
/>
426+
427+
const StyledWithAs = styled('div')`
428+
display: flex;
429+
`
430+
const Section = styled('section')`
431+
color: hotpink;
432+
`
433+
;<StyledWithAs as="section" />
434+
;<StyledWithAs as={Section} />

0 commit comments

Comments
 (0)