Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return type of generic function

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading