The following code example illustrates an issue where TypeScript is unable to infer the generic type U
in the fooBar
function, leading to the return type of fooRef.doIt()
being unknown
. What is the reason for this behavior and what modifications are required to obtain the correct return type?
interface Foo<T> {
foo(): T;
}
class Bar implements Foo<string> {
foo(): string {
return 'Bar';
}
}
class Baz implements Foo<number> {
foo(): number {
return 43;
}
}
class FooRef<T extends Foo<U>, U> {
constructor(private instance: T) {}
doIt() {
return this.instance.foo();
}
}
function fooBar<T extends Foo<U>, U>(foo: new (...args: any[]) => T) {
return new FooRef(new foo());
}
const barRef = fooBar(Bar);
barRef.doIt(); // unknown, expected string
const bazRef = fooBar(Baz);
bazRef.doIt(); // unknown, expected number