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

71 Views Asked by At

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

1

There are 1 best solutions below

0
Guerric P On BEST ANSWER

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