#Automatically get type from react parameter

5 messages · Page 1 of 1 (latest)

rigid knoll
#

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!

mossy zinc
#

this doesn't fully answer your question but one problem that immediately jumps out: i doubt you actually want extends [] in those constraints. [] is an empty tuple; you wouldn't be able to supply anything except [] to that really. you probably mean extends unknown[]?

#

could you throw a complete example into a playground and share the link? when i try to reproduce i'm seeing other issues that i'm not sure are legitimate or just artifacts of trying to reproduce from incomplete information

#

i suppose i am especially interested in the type signature of Api.getGroupData

rigid knoll
#

the getGroupData function is just this:

    export function getGroupData(): RequestProcessor<[groupId: number], GroupData> {
        return (([groupId]) => {
            return makeApiRequest("GET", "/groups/{id}", {}, { "{id}": groupId.toString() })
        })
    }