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

Time:12-28

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

CodePudding user response:

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

  • Related