[英]Typescript pass generic to Map
I want to pass a generic type from the child class to a property. 我想将泛型类型从子类传递到属性。
interface MyInterface {
method(): void;
}
class B<P> {
entities = new Map<number, P>();
}
class C<P = MyInterface> extends B<P> {
click() {
this.entities.get(1).method();
}
}
I'm expecting each entity to be of type MyInterface
, but I'm getting a type error: 我期望每个实体的类型
MyInterface
,但是出现类型错误:
Property method() doesn't exist on type P
属性method()在P类型上不存在
What is the issue? 有什么问题
Just because P = MyInterface
does not mean any passed in P
must extend MyInterface
. 仅仅因为
P = MyInterface
并不意味着在P
传递的任何内容都必须扩展MyInterface
。 For example with no other constraints, this would also be valid: 例如,在没有其他约束的情况下,这也将是有效的:
new C<{ noMethod() : void }>();
You need to add a constraint to P
to say that any passed in P
must extend MyInterface
, and you can keep MyInterface
as a default as well. 您需要向
P
添加一个约束,以使任何传入P
必须扩展MyInterface
,并且您也可以将MyInterface
保留为默认值。
interface MyInterface {
method(): void;
}
class B<P> {
entities = new Map<number, P>();
}
class C<P extends MyInterface = MyInterface> extends B<P> {
click() {
this.entities.get(1).method();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.