From a2c314c5de1cb4fc0e7334d37d022e5ef84465e3 Mon Sep 17 00:00:00 2001 From: Igor Oleinikov Date: Fri, 4 Jan 2019 16:30:02 -0800 Subject: [PATCH] [styled-components] Add support of `defaultProps` --- types/styled-components/index.d.ts | 5 ++++ types/styled-components/test/index.tsx | 37 ++++++++++++++++++++++++-- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/types/styled-components/index.d.ts b/types/styled-components/index.d.ts index ca3ff22c0e..6c3ec7b1de 100644 --- a/types/styled-components/index.d.ts +++ b/types/styled-components/index.d.ts @@ -109,6 +109,9 @@ type ForwardRefExoticBase

= Pick< keyof React.ForwardRefExoticComponent >; +// extracts React defaultProps +type ReactDefaultProps = 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 @@ -141,6 +144,8 @@ export interface StyledComponentBase< // props: StyledComponentPropsWithAs // ): React.ReactElement> + defaultProps: ReactDefaultProps; + // TODO (TypeScript 3.2): delete this overload ( props: StyledComponentProps & { diff --git a/types/styled-components/test/index.tsx b/types/styled-components/test/index.tsx index 0c175d8ce9..710c5f2070 100644 --- a/types/styled-components/test/index.tsx +++ b/types/styled-components/test/index.tsx @@ -270,7 +270,7 @@ const MyOtherComponentWithProps = () => ( // Create a react component that renders an // which takes extra props passed as a generic type argument -const LinkFromStringWithPropsAndGenerics = styled("a")` +const LinkFromStringWithPropsAndGenerics = styled("a") ` 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 { + static defaultProps = { + optionalProp: 'fallback' + }; + + render() { + const { requiredProp, optionalProp } = this.props; + return ( + + {requiredProp.toString()} + {optionalProp.toString()} + + ); + } + } + + const StyledComponent = styled(MyComponent)` + color: red + `; + + ; + ; + ; + // still respects the type of optionalProp + ; // $ExpectError +}