在下面的示例中,Typescript 可以推断出 T
的类型在方法中foo
来自 bar
中传递给它的参数, 但它不推断 R
的类型,感觉应该是这样——因为它知道 T
的类型还有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());
还有其他方法吗?
最佳答案
第一个问题是你的接口(interface)是空的, typescript 使用结构类型,所以如果你的通用接口(interface)不使用它的类型参数,它有它并不重要。例如,这有效:
interface I<T> { }
declare let foo: I<string>
declare let bar: I<number>
// Same structure ({}), assignment works
foo = bar
bar = foo
如果我们添加一个字段,Typescript 仍然不会推断出 R
类型参数,它只是不会尝试从 T
中提取它。最好的选择是使用条件类型并在需要的地方提取泛型类型参数:
interface I<T> {
value :T
}
class A implements I<string> {
value! :string
}
type ExtractFromI<T extends I<unknown>> = T extends I<infer U> ? U : never;
function foo<T extends I<unknown>>(bar: T): ExtractFromI<T>{
return bar.value as ExtractFromI<T>; // Generic type with unresolved type parameters, we need a type assertion to convince the compiler this is ok
}
var r = foo(new A()); // string
关于typescript - 未推断出扩展接口(interface)的通用类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53448100/