[英]Create generic interface that accepts type of objects as arguments
我有以下内容:
interface Pet {
a: A,
b: B[]
}
interface NotPet {
a: A,
b: B
}
interface A {
desc: string
}
interface B {
name: string
}
interface DataStore<T> {
addItem(type: T[keyof T]);
}
class Shop implements DataStore<Pet> {
addItem(type: Pet[keyof Pet]) {
//add type A or add type B
}
passToAddItem(itemToPass: A | B) {
this.addItem(itemToPass); //<-- this expects either A | B[]
}
}
class OtherShop implements DataStore<NotPet> {
addItem(type: NotPet[keyof NotPet]) {
}
passToAddItem(itemToPass: A | B) {
this.addItem(itemToPass); //<-- this works just fine
}
}
上面强调了这个问题。 我想要通用方法来接受 A | B.. 但在当前形式下,它接受 A | 乙[]。
我希望能够将 A 或 B(不是 B[])传递给 addItem 方法。 我理解为什么它需要一个数组,但不知道如何解决这个问题。
我收到的错误来自 IDE:“B”类型的参数不可分配给“A”类型的参数 | 乙[]'。
我不明白你期望它做什么,它完全按照你的要求做,即将 T 类型绑定到成员的 T 类型之一,就像你说的你明白这一点。 所以解决方案是:
我真的不喜欢 2. 和 3.
编辑:对不起,我花了这么长时间再次回答,工作孩子和生活:) 阅读评论后,在我看来,您的设计有点偏离,您可以使用以下方法解决它:
class Shop implements DataStore<NotPet>, Pet {
a: A;
b: B[];
addItem(type: NotPet[keyof NotPet]) {
//add type A or add type B
}
passToAddItem(itemToPass: A | B) {// or you just directly use addItem
this.addItem(itemToPass); //<-- this now works
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.