![](/img/trans.png)
[英]Typescript, Is it possible to add method to external class prototype?
[英]How to add a method to a prototype of a generic class in typescript
我正在嘗試將方法添加到PromiseLike<T>
With String
的原型中,這不是問題:
declare global {
interface String {
handle(): void;
}
}
String.prototype.handle = function() {
}
編譯正常
但是,如果我嘗試對PromiseLike<T>
執行相同操作, PromiseLike<T>
收到編譯錯誤'PromiseLike' only refers to a type, but is being used as a value here.
:
declare global {
interface PromiseLike<T> {
handle(): PromiseLike<T>;
}
}
PromiseLike.prototype.handle = function<T>(this: T):T {
return this;
}
顯然,這里的問題是PromiseLike
是泛型的。 我怎樣才能在打字稿中正確地做到這一點?
接口在運行時不存在,它們在編譯期間會被擦除,因此無法在接口上設置函數的值。 您可能正在尋找的是將函數添加到Promise
。 您可以類似地執行此操作:
declare global {
interface Promise<T> {
handle(): Promise<T>;
}
}
Promise.prototype.handle = function<T>(this: Promise<T>): Promise<T> {
return this;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.