How can we create extension methods for non-global interfaces in TypeScript?

Viewed 1788

I'm currently learning TypeScript but am thoroughly stumped at how to implement extension methods for non-global interfaces. Consider the following example: say I have an interface defining a Cart like so:

interface Cart {
    id(): string,
    name(): string,
    quantity(): number

    /* Other methods */
}

Then, I'd like to add an extension method similar to the following:

Cart.prototype.isValid = function() {
    return this.quantity() > 0;
}

This obviously doesn't work since Cart is not a type but I'm confused because Promise is also defined as an interface, yet I can successfully add extension methods to it. For example:

declare global {
    interface Promise<T> {
        hello(): string
    }
}

Promise.prototype.hello = function() {
    return "Hello!";
}

export {};

Is it possible to extend non-global interfaces like Cart and if so, how do I do it?

1 Answers

In your case, Cart is just a type. There's no object, you can't extend a prototype of a type/interface ref. There's no prototype to extend, you could do it with some object that implements Cart.

In the case of Promise, it's a browser API, if you got to you console on the Browser and type Promise you will see you have a object there. When you extend promise prototype like the example you gave you are not extending the interface but this object provided.

One possible solution if you want to do so is interface composition like:

interface CartSpecial extends Cart {
    ...
}
Related