I'm using knockout 3.x with Typescript and I want to make a strongly typed collection class that inherits from KnockoutObservableArray<T>
, so that my type can BE an observable array but also have its own methods. So I tried this:
export class Emails implements KnockoutObservableArray<Email>
{
//add a new email to the list
addItem() : void
{
var email = new ContactEmail();
...
this.push(email);
};
}
But this gives me the following error:
Class Emails declares interface KnockoutObservableArray<Email> but does not implement it:
Type 'Emails' is missing property 'extend' from type 'KnockoutObservableArray<Email>'.
If I try to add the extend
method, then it requires that I implement the peek
method, and so on, suggesting that I need to implement all of KnockoutObservableArray
. But I don't want to reimplement it, I want to extend it, and since KnockoutObservableArray
is an interface and not a class, I don't see any way to do that. Is there a way?
The
implements
keyword is used to state that you will implement the supplied interface... to satisfy this condition, you'll need to implement all of the methods defined in the following interfaces (because you need to follow the whole chain fromKnockoutObservableArray<T>
.Alternatively, create a smaller interface to represent what you actually need from your custom class, and if it is a sub-set of all of this, you will be able to use your interface for your custom class as well as for normal
KnockoutObservableArray<T>
classes (which will pass the interface test structurally).Here is an example of the alternative... assuming you need
push
andremove
as an example. (Side note: inheritance isn't possible here as these are all interfaces - if Knockout supports inheritance, the type definition could be changed to allow the work-freeextends
rather than the hard workimplements
version of this answer...)The interesting bit in this example is the first interface - it is a custom one you define, but anything that matches it will do, including a
KnockoutObservableArray<Email>
. This is an example of structural typing saving you some time. Structural typing wants you to go to the pub.