【发布时间】:2019-04-11 07:42:27
【问题描述】:
我目前正在学习 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 这样的非全局接口,如果可以,我该怎么做?
【问题讨论】:
-
不要认为它可能或有用。在运行时不应更改接口。否则编译过程中将无法进行类型检查。
-
你可以做的是创建另一种类型,它将是几个接口的组合:
type Blah = Foo & Bar
标签: typescript extension-methods