gpt4 book ai didi

javascript - Typescript 将泛型传递给 Map

转载 作者:行者123 更新时间:2023-11-30 14:30:46 31 4
gpt4 key购买 nike

我想将泛型类型从子类传递给属性。

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

我希望每个实体都是 MyInterface 类型,但我收到类型错误:

Property method() doesn't exist on type P

问题是什么?

最佳答案

只是因为 P = MyInterface 并不意味着任何传入 P 的东西都必须扩展 MyInterface。例如,在没有其他约束的情况下,这也是有效的:

new C<{ noMethod() : void }>();

你需要给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();
}
}

关于javascript - Typescript 将泛型传递给 Map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51206562/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com