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

TypeScript inference not working on nested generics, infers type as unknown

I need TypeScript to correctly infer the type T in the return value of my "wrongInference" function.

interface Foo {
  bar: string;
}

const paramFunction = (bar: string): Foo => ({
  bar
});

type GenericFunction<T> = (...args: any) => T;

export const wrongInference = <T, F extends GenericFunction<T>>(
  paramFunction: F
) => ({
  data: {} as T,
});

const wrongType = wrongInference(paramFunction);

TypeScript infers the data value as unknown. Is there any way around this?

enter image description here

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 :

Here is how you could fix your problem with a conditional return type and the infer keyword:

interface Foo {
    bar: string;
}

const paramFunction = (bar: string): Foo => ({
    bar
});

type GenericFunction<T> = (...args: any) => T;

export const wrongInference = <F extends GenericFunction<any>>(
    paramFunction: F
): F extends GenericFunction<infer T> ? { data: T } : never => ({
    data: {},
} as any);

const wrongType = wrongInference(paramFunction);

TypeScript playground

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