score:-4

tsx doesn't seem to play well with type arguments in props.

you should set a default type param value, such as any, but that will just assume your types are always any when using the component, which might not be exactly what you want:

export interface props<t = any> {
  value: t;
  valuecallback: (t: t) => void;
}

// ...

// `valuecallback` will pass an explicit `any`
<typedcomponent value={value} valuecallback={setstate} />

you could try copying it with the valid extended type, and then using that, e.g.:

import { props as tcprops } from './typedcomponent'
const stronglytypedcomponent: react.component<tcprops<string>> = typedcomponent

// ...

// correctly typed, but more verbal
<stronglytypedcomponent value={value} valuecallback={setstate} /> 

score:1

not the ideal solution, but i was able to achieve this by exporting the component's type, and then using that to cast the result of react.lazy

export type typedcomponenttype = typeof typedcomponent;

and then

import type { typecomponent } from './typedcomponent';
const typedcomponent = lazy(() => import("./typedcomponent")) as typedcomponenttype;

score:2

tl;dr: you can override react.lazy type definition to support generics.

react.d.ts:

declare namespace react {
  function lazy<t extends componenttype<any>>(
    factory: () => promise<{ default: t }>,
  ): t;
}

explanation: original react.lazy declaration looks like this:

function lazy<t extends componenttype<any>>(
  factory: () => promise<{ default: t }>
): lazyexoticcomponent<t>;

it returns lazyexoticcomponent type, which is superset of exoticcomponent. unfortunately, this interface is written in way which don't support generics. however, according to comment above the interface, it is meant only for internal distinction between "regular" and other components, like results of lazy and memo calls; in jsx syntax there's no difference between this exoticcomponent and component. that's why we can safely omit laxyexoticcomponent type in our custom override and make use of generics.


Related Query

More Query from same tag