在打字稿中,为什么我不能推断出泛型超类型的类型参数?

问题描述 投票:0回答:1

我希望能够显式定义一个

Base
arg 并将其与继承自类
Closure
的类型一起使用。

abstract class Closure<Base> {
    // Helper functions/types etc. related to Base here
}

所以如果我有一个类,我可以明确地用类型标记它,以便以后使用它。

interface A {
    foo(args: { one: string, two: number }): void
}

class B extends Closure<A> implements A {
    foo(args: { one: string, two: number }) { }
}

我创建了一个类型来推断

Base
类型在任何实现
Closure
的实例上。

type BaseOf<T extends Closure<unknown>> = T extends Closure<infer U> ? U : never;

但是当我尝试推断

Base
类型时,我得到
unknown
.

type b = BaseOf<B> // Why is this unknown?

然而...

type b2 = BaseOf<Closure<A>> // This results in A just fine.

当我明确定义具体类型时,为什么我不能在这里推断

A

typescript typescript-generics
1个回答
0
投票

感谢 vr,我最终得到了这个解决方案:

abstract class Closure<Base> {
    private readonly _base?: Base;
}

这确保每个泛型类型实例在名义上由其类型参数指定类型!

© www.soinside.com 2019 - 2024. All rights reserved.