-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Building Strongly Typed Polymorphic Components (#18274)
* feat: adding reusable polymorphicProps * feat: added PolymorphicProps to a new file * fix: fixed commnets * fix: fixed type error by ommiting ref
- Loading branch information
Showing
3 changed files
with
79 additions
and
49 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
type AsProp<C extends React.ElementType> = { | ||
as?: C; | ||
}; | ||
|
||
type PropsToOmit<C extends React.ElementType, P> = keyof (AsProp<C> & P); | ||
|
||
// This can be used if there is NO need for "ref" | ||
export type PolymorphicComponentProp< | ||
C extends React.ElementType, | ||
Props = {}, | ||
> = React.PropsWithChildren<Props & AsProp<C>> & | ||
Omit<React.ComponentPropsWithoutRef<C>, PropsToOmit<C, Props>>; | ||
|
||
// This is the type for the "ref" only | ||
export type PolymorphicRef<C extends React.ElementType> = | ||
React.ComponentPropsWithRef<C>['ref']; | ||
|
||
// This is a new type utitlity with ref! | ||
export type PolymorphicComponentPropWithRef< | ||
C extends React.ElementType, | ||
Props = {}, | ||
> = PolymorphicComponentProp<C, Props> & { ref?: PolymorphicRef<C> }; |