Skip to content

Commit

Permalink
fix: Infer propertly the own props in complex polymorphic components
Browse files Browse the repository at this point in the history
  • Loading branch information
GianlucaGuarini committed Oct 10, 2024
1 parent 0cf138e commit d22a170
Show file tree
Hide file tree
Showing 5 changed files with 119 additions and 102 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ jobs:

strategy:
matrix:
node-version: [18.x]
node-version: [18.x, 20.x, 22.x]
# See supported Node.js release schedule at https://nodejs.org/en/about/releases/

steps:
Expand Down
8 changes: 5 additions & 3 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ import type {
} from 'react';

// Utility type to merge two types
type Merge<T, U> = Omit<T, keyof U> & U;
type Merge<T, U> = {
[K in keyof T as K extends keyof U ? never : K]: T[K];
} & U;

// Props type with an "as" prop that allows specifying the element type
export type PropsWithAs<
Expand Down Expand Up @@ -42,14 +44,14 @@ export type PolymorphicExoticProps<
P,
T extends ElementType,
S extends keyof JSX.IntrinsicElements = keyof JSX.IntrinsicElements,
> = T extends ExoticComponent<infer U> ? PolymorphicProps<Merge<P, PropsWithoutAs<PropsWithoutRef<U>>>, T, S> : never;
> = T extends ExoticComponent<infer U> ? PolymorphicProps<Merge<PropsWithoutAs<PropsWithoutRef<U>>, P>, T, S> : never;

// Polymorphic props type for functional components
export type PolymorphicFunctionalProps<
P,
T extends ElementType,
S extends keyof JSX.IntrinsicElements = keyof JSX.IntrinsicElements,
> = T extends FC<infer U> ? PolymorphicProps<Merge<P, PropsWithoutAs<PropsWithoutRef<U>>>, T, S> : never;
> = T extends FC<infer U> ? PolymorphicProps<Merge<PropsWithoutAs<PropsWithoutRef<U>>, P>, T, S> : never;

// Type for the forwarded ref of a component
export type PolymorphicForwardedRef<C extends ElementType> = ComponentPropsWithRef<C>['ref'];
184 changes: 92 additions & 92 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,13 @@
"homepage": "https://github.com/axa-ch/react-polymorphic-types#readme",
"devDependencies": {
"@axa-ch/easy-config": "2.1.1",
"@biomejs/biome": "1.8.3",
"framer-motion": "^11.5.4",
"@biomejs/biome": "1.9.3",
"framer-motion": "^11.11.7",
"prettier": "3.3.3",
"typescript": "^5.6.2"
"typescript": "^5.6.3"
},
"dependencies": {
"@types/react": "^18.3.5",
"@types/react": "^18.3.11",
"react": "^18.3.1"
}
}
Loading

0 comments on commit d22a170

Please sign in to comment.