Skip to content

Commit

Permalink
Utility types Props and Components to reuse in another packages
Browse files Browse the repository at this point in the history
  • Loading branch information
gtkatakura committed Jul 29, 2020
1 parent 8c0de2a commit 14f5b07
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 14 deletions.
19 changes: 5 additions & 14 deletions src/index.tsx
Original file line number Diff line number Diff line change
@@ -1,29 +1,20 @@
import React, { forwardRef, Ref, PropsWithoutRef } from 'react'
import React, { forwardRef, Ref } from 'react'
import { Button as A11yButton, ButtonProps as A11yProps } from 'reakit'
import { PropsWithAs, As } from 'reakit-utils/types'
import {
Button as ThemeAwareButton,
ButtonProps as ThemeAwareProps,
} from 'theme-ui'
import { As, Props, Component } from '@vtex-components/types'

type Component<DefaultAs extends As, DefaultProps> = {
<T extends As = DefaultAs>(
props: PropsWithAs<PropsWithoutRef<DefaultProps>, T>
): JSX.Element
}

type ButtonProps = A11yProps & { as?: As }
type ButtonProps<T extends As = typeof ThemeAwareButton> = Props<T, A11yProps>

const Button = (
{ as = ThemeAwareButton, ...props }: ButtonProps,
{ as = ThemeAwareButton, ...props }: ButtonProps<As>,
ref: Ref<As>
) => {
return <A11yButton ref={ref} as={as} {...props} />
}

export { ButtonProps, A11yProps, ThemeAwareProps }

export default forwardRef(Button) as Component<
typeof ThemeAwareButton,
A11yProps
>
export default forwardRef(Button) as Component<ButtonProps>
24 changes: 24 additions & 0 deletions src/typings.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,27 @@ declare module '*.svg' {
export default svgUrl
export { svgComponent as ReactComponent }
}

declare module '@vtex-components/types' {
import { PropsWithoutRef } from 'react'
import { As, PropsWithAs } from 'reakit-utils/types'

export { As }

export type Props<T extends As, BaseProps> = PropsWithAs<
PropsWithoutRef<BaseProps>,
T
>

export type AsOf<T> = T extends Props<infer TAs, any> ? TAs : never

export type BasePropsOf<T> = T extends Props<any, infer TProps>
? TProps
: never

export type Component<DefaultProps extends Props<any, any>> = {
<T extends As = AsOf<DefaultProps>>(
props: Props<T, BasePropsOf<DefaultProps>> & { as?: T }
): JSX.Element
}
}

0 comments on commit 14f5b07

Please sign in to comment.