Currently diving into TypeScript, I find myself stuck when trying to implement extension methods for non-global interfaces. To illustrate, let's take a look at an interface
that defines a Cart
:
interface Cart {
id(): string,
name(): string,
quantity(): number
/* Other methods */
}
My goal is to introduce an extension method similar to the following:
Cart.prototype.isValid = function() {
return this.quantity() > 0;
}
This approach hits a roadblock because Cart
is not a type. However, what puzzles me is that even though `Promise` is also declared as an interface
, I am able to successfully add extension methods to it. For instance:
declare global {
interface Promise<T> {
hello(): string
}
}
Promise.prototype.hello = function() {
return "Hello!";
}
export {};
So, my question is: Is there a way to extend non-global interfaces like Cart
, and if so, how can I achieve this?