Home > database >  Return type of generic function
Return type of generic function

Time:04-30

I'm trying to make getResults function return the proper type, but currently stuck with this:

interface IResponse<T> {
    result: T;
}

type FnType<P, R> = (params: P) => R;

const r1: IResponse<string[]> = { result: ['123'] };
const r2: IResponse<number[]> = { result: [456] };

const getResults = <T, R extends IResponse<T[]>, P>(fn: FnType<P, R>, params: P): T[] => {
    return [
        ...fn(params).result,
        ...fn(params).result
    ];
};

const getValue = <T>(r: IResponse<T>) => r;

// returned type is unknown[]
// how can we make it return string[]?
getResults(getValue, r1);

// returned type is unknown[]
// how can we make it return number[]?
getResults(getValue, r2);

Playground

The code is just an example, in the production getResults function is used to merge results from a paginated request (fn in this case is a request function)

CodePudding user response:

So, I'm not sure this will also cover the things you need for production. But the return type looks alright like this:

interface IResponse<T> {
    result: T;
}

type FnType<P, R> = (params: P) => R;

const r1: IResponse<string[]> = { result: ['123'] };
const r2: IResponse<number[]> = { result: [456] };

const myResults = <P,R>(fn: FnType<P,IResponse<R[]>>, params: P): R[] => {
     return [
        ...fn(params).result,
        ...fn(params).result
    ];
}

const getValue = <T>(r: IResponse<T>) => r;

myResults(getValue, r1);

myResults(getValue, r2);

Playground link

Edit: I'm actually not exactly sure why the code in question does not give correct IntelliSense, it makes sense to me.

But what I can see is that you used three generic types T, R and P. My Idea is that basically you only have 2 types to worry about which are params and the Result of the method.

I basically say, whatever type is inside the getValue's IResponse will be the final output of the myResults function.

  • Related