Skip to content

Commit

Permalink
Added basic TS type support for as prop on styled components (#1874)
Browse files Browse the repository at this point in the history
* Add type for as prop

* Add changeset

* Simplify type for `as` prop

* Tweak changeset

Co-authored-by: Mateusz Burzyński <mateuszburzynski@gmail.com>
  • Loading branch information
connor-baer and Andarist committed Jul 9, 2020
1 parent 6d32d82 commit 4d3b60d
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 4 deletions.
5 changes: 5 additions & 0 deletions .changeset/cyan-jobs-carry.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@emotion/styled': minor
---

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.
21 changes: 17 additions & 4 deletions packages/styled/types/base.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,12 +106,22 @@ export interface CreateStyled {
>(
component: C,
options: FilteringStyledOptions<PropsOf<C>, ForwardedProps>
): CreateStyledComponent<Pick<PropsOf<C>, ForwardedProps> & { theme?: Theme }>
): CreateStyledComponent<
Pick<PropsOf<C>, ForwardedProps> & {
theme?: Theme
as?: React.ElementType
}
>

<C extends React.ComponentType<React.ComponentProps<C>>>(
component: C,
options?: StyledOptions<PropsOf<C>>
): CreateStyledComponent<PropsOf<C> & { theme?: Theme }>
): CreateStyledComponent<
PropsOf<C> & {
theme?: Theme
as?: React.ElementType
}
>

<
Tag extends keyof JSX.IntrinsicElements,
Expand All @@ -120,14 +130,17 @@ export interface CreateStyled {
tag: Tag,
options: FilteringStyledOptions<JSX.IntrinsicElements[Tag], ForwardedProps>
): CreateStyledComponent<
{ theme?: Theme },
{ theme?: Theme; as?: React.ElementType },
Pick<JSX.IntrinsicElements[Tag], ForwardedProps>
>

<Tag extends keyof JSX.IntrinsicElements>(
tag: Tag,
options?: StyledOptions<JSX.IntrinsicElements[Tag]>
): CreateStyledComponent<{ theme?: Theme }, JSX.IntrinsicElements[Tag]>
): CreateStyledComponent<
{ theme?: Theme; as?: React.ElementType },
JSX.IntrinsicElements[Tag]
>
}

declare const styled: CreateStyled
Expand Down
9 changes: 9 additions & 0 deletions packages/styled/types/tests-base.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -423,3 +423,12 @@ const StyledButton = StyledDiv.withComponent('button')
e
}}
/>

const StyledWithAs = styled('div')`
display: flex;
`
const Section = styled('section')`
color: hotpink;
`
;<StyledWithAs as="section" />
;<StyledWithAs as={Section} />

0 comments on commit 4d3b60d

Please sign in to comment.