Skip to content

Instantly share code, notes, and snippets.

@itsjavi
Created March 20, 2023 09:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save itsjavi/d125af805638826cc1dda86b9cf20f84 to your computer and use it in GitHub Desktop.
Save itsjavi/d125af805638826cc1dda86b9cf20f84 to your computer and use it in GitHub Desktop.
Polymorphic component props
import React from 'react'
type PolymorphicPropsFactory<T, P> = {
as?: T | React.ElementType
children?: React.ReactNode | undefined
className?: string | undefined
} & React.RefAttributes<T> &
P
export type PolymorphicProps<T, FallbackPropsType> =
// as = Function Component
T extends React.FunctionComponent<infer P>
? PolymorphicPropsFactory<T, P>
: // as = Class Component
T extends React.ComponentClass<infer P>
? PolymorphicPropsFactory<T, P>
: // as = HTML Tag
T extends string
? PolymorphicPropsFactory<T, React.HTMLAttributes<T>>
: // ... fallback
PolymorphicPropsFactory<T, FallbackPropsType>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment