Strengthen type of ReactType to also validate intrinsic elements

This commit is contained in:
Jessica
2018-11-23 15:10:09 +09:00
parent c2fac6d235
commit 4dd9510a50
2 changed files with 15 additions and 4 deletions
+8 -4
View File
@@ -50,7 +50,11 @@ declare namespace React {
// React Elements
// ----------------------------------------------------------------------
type ReactType<P = any> = string | ComponentType<P>;
type ReactType<P = any> =
{
[K in keyof JSX.IntrinsicElements]: P extends JSX.IntrinsicElements[K] ? K : never
}[keyof JSX.IntrinsicElements] |
ComponentType<P>;
type ComponentType<P = {}> = ComponentClass<P> | FunctionComponent<P>;
type Key = string | number;
@@ -713,17 +717,17 @@ declare namespace React {
* NOTE: prefer ComponentPropsWithRef, if the ref is forwarded,
* or ComponentPropsWithoutRef when refs are not supported.
*/
type ComponentProps<T extends keyof JSX.IntrinsicElements | ComponentType<any>> =
type ComponentProps<T extends ReactType> =
T extends ComponentType<infer P>
? P
: T extends keyof JSX.IntrinsicElements
? JSX.IntrinsicElements[T]
: {};
type ComponentPropsWithRef<T extends keyof JSX.IntrinsicElements | ComponentType<any>> =
type ComponentPropsWithRef<T extends ReactType> =
T extends ComponentClass<infer P>
? PropsWithoutRef<P> & RefAttributes<InstanceType<T>>
: PropsWithRef<ComponentProps<T>>;
type ComponentPropsWithoutRef<T extends keyof JSX.IntrinsicElements | ComponentType<any>> =
type ComponentPropsWithoutRef<T extends ReactType> =
PropsWithoutRef<ComponentProps<T>>;
// will show `Memo(${Component.displayName || Component.name})` in devtools by default,
+7
View File
@@ -325,3 +325,10 @@ type ImgPropsWithRefRef = ImgPropsWithRef['ref'];
type ImgPropsWithoutRef = React.ComponentPropsWithoutRef<'img'>;
// $ExpectType false
type ImgPropsHasRef = 'ref' extends keyof ImgPropsWithoutRef ? true : false;
const HasClassName: React.ReactType<{ className?: string }> = 'a';
const HasFoo: React.ReactType<{ foo: boolean }> = 'a'; // $ExpectError
const HasFoo2: React.ReactType<{ foo: boolean }> = (props: { foo: boolean }) => null;
const HasFoo3: React.ReactType<{ foo: boolean }> = (props: { foo: string }) => null; // $ExpectError
const HasHref: React.ReactType<{ href?: string }> = 'a';
const HasHref2: React.ReactType<{ href?: string }> = 'div'; // $ExpectError