【发布时间】:2016-11-11 18:00:42
【问题描述】:
我有一个通讯录和两种类型的联系人:
- 人员
- 组织
它们都扩展了 Contact 类。
我想要一个类的方法返回一个联系人数组。
public method(args...): Array<Contact> {...}
很好,但是如果我有那个方法来对数组内的联系人的某些属性做一些事情呢?
public method(args...): Array<Contact> {
contacts :Array<Contact> = getContactsFromSomewhere();
contacts.forEach( contact => {
if(typeof contact === "Person"){ //persons and organizations are different, they have different atrributes
//Here i modify some Person attributes
}
else{
//Here i modify some Organization attributes
});
return contacts;
这感觉很麻烦,难以阅读。 为什么不这样呢?
public method(args...): Array<T extends Contact> {
contacts :Array<T extends Contact> = getContactsFromSomewhere();
contacts.forEach( contact => {
contact.doSomething() //abstract method implemented in both classes its own way.
});
return contacts;
不可能,我做不到
Array<T extends Contact>
这个错误是 VSCode 抛出的:
[ts] 泛型“数组”需要 1 个类型参数
是否可以使用使用泛型类的数组来扩展打字稿中的另一个类?
【问题讨论】:
标签: typescript angular