Ruben
Ruben

Reputation: 489

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

Upvotes: 0

Views: 98

Answers (1)

Guerric P
Guerric P

Reputation: 31805

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

Upvotes: 2

Related Questions