In the following example Typescript can infer the type of T
in method foo
from the parameter passed to it in bar
, but it doesn't infer the type of R
, which it feels like it should - given that it knows the type of T
and also that T extends I<R>
interface I<T> {
}
class A implements I<string> {
}
function foo<T extends I<R>, R>(bar: T): R {
return;
}
foo(new A());
Is there another way to do this?
The first problem is that your interface is empty, typescript uses structural typing so if your generic interface will not use it's type parameter it won't matter much that it has it. For example this works:
Event if we add a field, Typescript will still not infer the
R
type parameter, it just doesn't try to extract it fromT
. Your best option is to use a conditional type and extract the generic type parameter where you need it: