I have an address book and two types of Contacts:
- Persons
- Organizations
Both of them extends Contact class.
I want a method of a class to return an array of contacts.
public method(args...): Array<Contact> {...}
Nice, but what if i have that method to do something with some properties of the Contacts inside the array?
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;
This feels cumbersome, difficult to read. Why not something like this?
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;
Impossible, i can't do this
Array<T extends Contact>
This error is thrown by VSCode:
[ts] Generic type 'Array' requires 1 type argument(s)