无法推断扩展接口的通用类型 [英] Generic type of extended interface not inferred

查看:82
本文介绍了无法推断扩展接口的通用类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的示例中,Typescript可以根据在bar中传递给它的参数来推断方法foo中的T的类型,但是不能推断出R的类型应该-鉴于它知道T的类型以及T extends I<R>

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());

还有另一种方法吗?

推荐答案

第一个问题是您的接口为空,typescript使用结构化类型,因此,如果您的通用接口不使用它的type参数,那么它就没有多大关系了有它.例如,这有效:

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:

interface I<T> { }
declare let foo: I<string> 
declare let bar: I<number>
// Same structure ({}), assignment works
foo = bar
bar = foo 

事件,如果我们添加一个字段,Typescript仍不会推断R类型参数,只是不尝试从T中提取它.最好的选择是使用条件类型,然后在需要的地方提取泛型类型参数:

Event if we add a field, Typescript will still not infer the R type parameter, it just doesn't try to extract it from T. Your best option is to use a conditional type and extract the generic type parameter where you need it:

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

这篇关于无法推断扩展接口的通用类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆