Add support for forwardedAs to styled-components (#41347)

* Add support for forwardedAs to styled-components

* Test whether as/forwardedAs correctly rejects invalid props

* Revert "Test whether as/forwardedAs correctly rejects invalid props"

The newly added tests pass locally, but fail in automated testing, as per the comment on another case in test/index.tsx:580.

This reverts commit d09acb1eba6250b0761b2d626ce52d8e7df64310.
This commit is contained in:
Dominik Rowicki
2020-01-07 01:07:28 +01:00
committed by Armando Aguirre
parent 1100f122e4
commit dc4340f3da
4 changed files with 22 additions and 3 deletions

View File

@@ -89,7 +89,7 @@ type StyledComponentPropsWithAs<
T extends object,
O extends object,
A extends keyof any
> = StyledComponentProps<C, T, O, A> & { as?: C };
> = StyledComponentProps<C, T, O, A> & { as?: C, forwardedAs?: C };
export type FalseyValue = undefined | null | false;
export type Interpolation<P> =
@@ -190,6 +190,7 @@ export interface StyledComponentBase<
* String types need to be cast to themselves to become literal types (as={'a' as 'a'}).
*/
as?: keyof JSX.IntrinsicElements | React.ComponentType<any>;
forwardedAs?: keyof JSX.IntrinsicElements | React.ComponentType<any>;
}
): React.ReactElement<StyledComponentProps<C, T, O, A>>;

View File

@@ -590,6 +590,15 @@ const asTest = (
</>
);
const ForwardedAsNestedComponent = styled.div``;
const ForwardedAsComponent = styled(ForwardedAsNestedComponent)``;
const forwardedAsTest = (
<>
<ForwardedAsComponent forwardedAs="h2" />
<ForwardedAsComponent forwardedAs={WithComponentH2} />
</>
);
interface TestContainerProps {
size: "big" | "small";
test?: boolean;

View File

@@ -75,7 +75,7 @@ type StyledComponentPropsWithAs<
T extends object,
O extends object,
A extends keyof any
> = StyledComponentProps<C, T, O, A> & { as?: C };
> = StyledComponentProps<C, T, O, A> & { as?: C, forwardedAs?: C };
export type FalseyValue = undefined | null | false;
export type Interpolation<P> =
@@ -155,7 +155,7 @@ export interface StyledComponentBase<
> extends ForwardRefExoticBase<StyledComponentProps<C, T, O, A>> {
// add our own fake call signature to implement the polymorphic 'as' prop
(
props: StyledComponentProps<C, T, O, A> & { as?: never }
props: StyledComponentProps<C, T, O, A> & { as?: never, forwardedAs?: never }
): React.ReactElement<StyledComponentProps<C, T, O, A>>;
<AsC extends keyof JSX.IntrinsicElements | React.ComponentType<any> = C>(
props: StyledComponentPropsWithAs<AsC, T, O, A>

View File

@@ -589,6 +589,15 @@ const asTest = (
</>
);
const ForwardedAsNestedComponent = styled.div``;
const ForwardedAsComponent = styled(ForwardedAsNestedComponent)``;
const forwardedAsTest = (
<>
<ForwardedAsComponent forwardedAs="h2" />
<ForwardedAsComponent forwardedAs={WithComponentH2} />
</>
);
interface TestContainerProps {
size: "big" | "small";
test?: boolean;