[styled-components] Add support of defaultProps

This commit is contained in:
Igor Oleinikov
2019-01-04 16:30:02 -08:00
parent b35434fe6f
commit a2c314c5de
2 changed files with 40 additions and 2 deletions
+5
View File
@@ -109,6 +109,9 @@ type ForwardRefExoticBase<P> = Pick<
keyof React.ForwardRefExoticComponent<any>
>;
// extracts React defaultProps
type ReactDefaultProps<C> = C extends { defaultProps: infer D; } ? D : never;
// any doesn't count as assignable to never in the extends clause, and we default A to never
export type AnyStyledComponent =
| StyledComponent<any, any, any, any>
@@ -141,6 +144,8 @@ export interface StyledComponentBase<
// props: StyledComponentPropsWithAs<AsC, T, O, A>
// ): React.ReactElement<StyledComponentPropsWithAs<AsC, T, O, A>>
defaultProps: ReactDefaultProps<C>;
// TODO (TypeScript 3.2): delete this overload
(
props: StyledComponentProps<C, T, O, A> & {
+35 -2
View File
@@ -270,7 +270,7 @@ const MyOtherComponentWithProps = () => (
// Create a <LinkFromStringWithPropsAndGenerics> react component that renders an <a>
// which takes extra props passed as a generic type argument
const LinkFromStringWithPropsAndGenerics = styled("a")<LinkProps>`
const LinkFromStringWithPropsAndGenerics = styled("a") <LinkProps>`
font-size: 1.5em;
text-align: center;
color: ${a => (a.canClick ? "palevioletred" : "gray")};
@@ -656,7 +656,7 @@ async function typedThemes() {
ThemeProvider,
ThemeConsumer
} = (await import("styled-components")) as any as ThemedStyledComponentsModule<
typeof theme
typeof theme
>;
const ThemedDiv = styled.div`
@@ -946,3 +946,36 @@ function validateArgumentsAndReturns() {
// $ExpectError
createGlobalStyle([]);
}
function validateDefaultProps() {
interface Props {
requiredProp: boolean;
optionalProp: string; // Shouldn't need to be optional here
}
class MyComponent extends React.PureComponent<Props> {
static defaultProps = {
optionalProp: 'fallback'
};
render() {
const { requiredProp, optionalProp } = this.props;
return (
<span>
{requiredProp.toString()}
{optionalProp.toString()}
</span>
);
}
}
const StyledComponent = styled(MyComponent)`
color: red
`;
<MyComponent requiredProp />;
<StyledComponent requiredProp optionalProp="x" />;
<StyledComponent requiredProp />;
// still respects the type of optionalProp
<StyledComponent requiredProp optionalProp={1} />; // $ExpectError
}