Last active
June 21, 2020 07:14
-
-
Save Yama-Tomo/9b0155c3c56f4f6005c5a6e0f05f172f to your computer and use it in GitHub Desktop.
extract props type of styled-componets
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as React from 'react'; | |
import { StyledComponent, StyledComponentProps } from 'styled-components'; | |
export type ExtractStyledComponentProps<SC> = SC extends StyledComponent< | |
infer C, | |
infer T, | |
infer O, | |
infer A | |
> | |
? StyledComponentProps<C, T, O, A> & { | |
as?: keyof JSX.IntrinsicElements | React.ComponentType<any>; | |
forwardedAs?: keyof JSX.IntrinsicElements | React.ComponentType<any>; | |
} | |
: never; | |
export type ComponentPropsWithStyledComponents<C> = C extends StyledComponent<any, any, any, any> | |
? ExtractStyledComponentProps<C> | |
: React.ComponentProps<C>; | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as React from 'react'; | |
import styled from 'styled-components'; | |
import { | |
ExtractStyledComponentProps, | |
ComponentPropsWithStyledComponents | |
} from '~/path/to/extract_props_type_of_styled-componets'; | |
const UiComponent: React.FC<{ hoge: string, fuga?: number }> = (props) => <div />; | |
const StyledUiComponent = styled(UiComponent)` | |
background-color: red; | |
`; | |
type Props = ExtractStyledComponentProps<typeof StyledUiComponent>; | |
const test = (props: Props) => { | |
const hoge = props.hoge // => string | |
const fuga = props.fuga // => number | undefined | |
const theme = props.theme // => {} | |
const as = props.as // => JSX.IntrinsicElements | React.ComponentType<any> | |
const forwardedAs = props.forwardedAs // => JSX.IntrinsicElements | React.ComponentType<any> | |
} | |
// ------------------------------------------------------------------------------------------ | |
// `Props 1` is the same type as` Props` | |
type Props1 = ComponentPropsWithStyledComponents<typeof StyledUiComponent>; | |
type Props2 = ComponentPropsWithStyledComponents<typeof UiComponent>; | |
const test2 = (props: Props2) => { | |
const hoge = props.hoge // => string | |
const fuga = props.fuga // => number | undefined | |
const children = props.children // => React.ReactNode | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment