【发布时间】:2018-11-28 09:40:29
【问题描述】:
例如,我有两个接口扩展第三个接口
interface Animal { /* name, etc */ };
interface Dog extends Animal { /* dog specific things */ }
interface Cat extends Animal { /* cat specific things */ }
我想为两个扩展类创建“模型”类, 简化数据库的工作
interface AnimalModel<A extends Animal> {
all(): Promise<A[]>;
get(id: string): Promise<A>;
create(user: A): Promise<void>;
}
我继续前进
class DogModel implements AnimalModel<Dog> {
// Expected TypeScript to complain, but it does not, because Cat does extend the animal?
async create(cat: Cat) { /* actual implementation, query the db */ }
}
我做错了什么?我希望class DogModel implements AnimalModel<Dog> 方法只接受和/或返回Dogs,但它可以是任何Animal。
ps:我正在考虑使用抽象类,所以我可能会以不同的方式解决它,这个问题仍然没有答案,我想了解我的代码有什么问题(这个问题中的那个)
【问题讨论】:
-
在提供的示例中,
Dog和Cat在结构上是等效的。只需添加一些鉴别器属性(例如type: 'dog'),你就会得到一个错误 -
Dog 和 Cat 不同,但只有可选参数,例如:
claw?: Claw
标签: typescript oop interface extends implements