I want to automatically get the types from something like this:
<FetchData processor={Api.getGroupData()} input={[0]}>
{ /* ... */ }
</FetchData>
My types:
export type RequestProcessor<TInput extends [], TResult extends {}> = (inputs: TInput) => Promise<TResult>
export function FetchData<TInput extends [], TResult extends {}>({
processor, input, children /* [...] */
}: {
processor: RequestProcessor<TInput, TResult>
input: TInput,
children: (data: TResult) => ReactNode
/* [...] */
}) { /* [...] */ }
Also tried:
// from https://stackoverflow.com/questions/44851268/how-to-extract-the-generic-parameter-from-a-type#50924506
export type ExtractRequestProcessorInput<Type> = Type extends RequestProcessor<infer X, infer Y> ? X : never
export type ExtractRequestProcessorResult<Type> = Type extends RequestProcessor<infer X, infer Y> ? Y : never
export function FetchData<TProcessor extends RequestProcessor<any, any>>({
processor, input, children /* [...] */
}: {
processor: TProcessor
input: ExtractRequestProcessorInput<TProcessor>
children: (data: ExtractRequestProcessorResult<TProcessor>) => ReactNode
/* [...] */
}) { /* [...] */ }
But for both of the solutions I have to explicitly define the generics like:
// From first FetchData fn
<FetchData<[groupId: 0], GroupData> processor={Api.getGroupData()} input={[0]}>
{ /* ... */ }
</FetchData>
Is there any way to not have to explicitly define the types? It does seem to work from a hook I've made
export function useApi<TInput extends [], TResult extends {}>(processor: RequestProcessor<TInput, TResult>) {
/* [...] */
}
const getUserData = useApi(Api.getCurrentUser()) // Works fine
Thanks!