首页 > 解决方案 > 我们如何在 TypeScript 中为非全局接口创建扩展方法?

问题描述

我目前正在学习 TypeScript,但对如何为非全局接口实现扩展方法感到非常困惑。考虑以下示例:假设我有一个这样的interface定义Cart

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

    /* Other methods */
}

然后,我想添加一个类似于以下的扩展方法:

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

这显然不起作用,因为Cart它不是一个类型,但我很困惑,因为Promise它也被定义为一个interface,但我可以成功地向它添加扩展方法。例如:

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

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

export {};

是否可以扩展非全局接口Cart,如果可以,我该怎么做?

标签: typescriptextension-methods

解决方案


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 {
    ...
}

推荐阅读