-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.d.ts
53 lines (46 loc) · 1.82 KB
/
index.d.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import type {
Attributes,
ComponentPropsWithRef,
ComponentPropsWithoutRef,
ElementType,
ExoticComponent,
FC,
JSX,
PropsWithoutRef,
} from 'react';
// Utility type to merge two types
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<P, T extends ElementType> = P & {
as?: T;
};
// Helper to get the polymorphic component props without the as attribute
// it will allow the composition of polymorphic components
export type PropsWithoutAs<T> = Omit<T, 'as'>;
// Polymorphic props type that merges the component-specific props with the "as" prop
export type PolymorphicProps<
P,
T extends ElementType,
S extends keyof JSX.IntrinsicElements = keyof JSX.IntrinsicElements,
> = Merge<
T extends keyof JSX.IntrinsicElements ? PropsWithoutRef<JSX.IntrinsicElements[T]> : ComponentPropsWithoutRef<T>,
// cover cases where the allowed ElementType and allowed DOM nodes overlap and are the same
T extends S ? PropsWithAs<P, S> : PropsWithAs<P, T>
> &
Attributes;
// Polymorphic props type for exotic components
export type PolymorphicExoticProps<
P,
T extends ElementType,
S extends keyof JSX.IntrinsicElements = keyof JSX.IntrinsicElements,
> = 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<PropsWithoutAs<PropsWithoutRef<U>>, P>, T, S> : never;
// Type for the forwarded ref of a component
export type PolymorphicForwardedRef<C extends ElementType> = ComponentPropsWithRef<C>['ref'];