Home > Software design >  Infer generic class type
Infer generic class type

Time:11-23

Suppose I have the follwing types:

type AnyFunction = (...args: any[]) => any;

abstract class Foo<F extends AnyFunction> {}

class Bar extends Foo<() => string> {}

I also have a function like this:

function foo<F extends AnyFunction>(foo: Foo<F>): void {}

Now, when I call foo(), I want to have proper type inferrence, i.e. when calling foo(new Bar()) I would expect the type () => string to be inferred as foo's generic parameter T. However, unexpectedly, TypeScript uses AnyFunction (the least specific type possible).

Is there a way to fix this? I need to be able to call foo() in the same way, but I also need T to be properly inferred as () => string.

CodePudding user response:

F is unused in the class. Unused type parameters are not a good idea since the type system is structural, so the structure of the class matters not the declaration, or the declared type parameter list in this case.

Use the type parameter and you will get the expected type:

type AnyFunction = (...args: any[]) => any;

abstract class Foo<F extends AnyFunction> {
    f!: F
}

class Bar extends Foo<() => string> {}

function foo<F extends AnyFunction>(foo: Foo<F>): void {}

foo(new Bar) // foo<() => string>(foo: Foo<() => string>)

Playground Link

  • Related