[英]Extending a generics class with nested generics
is there a way in typescript to extend a class in this way: 打字稿中是否有办法以这种方式扩展类:
class ChildClass<Wrapper<A>> extends SuperClass<A>
This doesn't work but the idea would be to wrap the generics type into a known construct. 这不起作用,但是想法是将泛型类型包装到已知的构造中。 Here are the docs: 这里是文档:
https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md
This sounds a bit similar to this issue: 这听起来有点类似于此问题:
Can you subclass a generics class with a specific typed class? 您可以使用特定的类型化类来继承泛型类吗?
I don't do much oop so I'm not very familiar with stuff like covariance and contravariance, any help would be appreciated. 我没有做太多事情,所以我对协方差和逆方差等东西不太熟悉,任何帮助都将不胜感激。
It maeks no sense to write ChildClass<Wrapper<A>>
before the extends, because there you declare the generic type parameters. 在扩展之前编写ChildClass<Wrapper<A>>
毫无意义,因为您在此处声明了通用类型参数。 That means you can give them a name and, if you need to, a constraint (for example ChildClass<A extends Wrapper>
). 这意味着您可以给他们起一个名字,并在需要时给它一个约束(例如ChildClass<A extends Wrapper>
)。 What does Wrapper<A>
mean in this context? 在这种情况下, Wrapper<A>
是什么意思? The compiler can make no sense of it. 编译器对此毫无意义。
What is absolutely possible is to use Wrapper<A>
on the other side of the extends , because there A
is not a (formal) type parameter , but a type argument . 绝对可能在扩展的另一侧使用Wrapper<A>
,因为A
不是(正式)类型参数 ,而是类型参数 。 That means you are using the type parameter previously defined and there you can generate new types with it. 这意味着您正在使用先前定义的type参数,并且可以在其中生成新类型。
So depending on what you actually want to do , there are two options for you: 因此,根据您实际要执行的操作 ,有两种选择供您选择:
A
is assignable to Wrapper
A
可分配给Wrapper
When you want to make sure the A
is a Wrapper
or a derived class, use a generic constraint: 当您要确保A
是Wrapper
或派生类时,请使用一般约束:
class ChildClass<A extends Wrapper> extends SuperClass<A>
A
is a type argument of Wrapper<>
A
是Wrapper<>
的类型参数
If Wrapper<>
is itself a generic class or interface and you want to use A
as its type argument, do this: 如果Wrapper<>
本身是泛型类或接口,并且您想使用A
作为其类型参数,请执行以下操作:
class ChildClass<A> extends SuperClass<Wrapper<A>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.