typescript - 我们如何在 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
,如果可以,我该怎么做?
解决方案
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 {
...
}
推荐阅读
- ios - 如何在 Swift 中保留时间的同时最好地将时间转换为双倍并返回
- javascript - 如何在 TypeScript 中创建本地模块
- java - Oauth 2.0 - 单个资源服务器但多个客户端应用程序
- php - 显示来自 json 的数据
- swift - 如何将数据从 tableViewCell 中的 api 传递到 swift 4 中的另一个 tableViewCell?
- sql - Access 中的 SQL 代码在 FROM 子句中显示错误
- c# - 如何使用 System.Linq.Expressions 实例化和设置动态类型的属性
- perl - Perl 找不到数据文件
- go - intellij golang 插件调试总是编译
- android - Holder.itemView.setOnClickListener onBindViewHolder 内的 AlertDialog Builder