Reputation: 8462
I'm trying to add a method to a prototype of PromiseLike<T>
With String
it is not a problem:
declare global {
interface String {
handle(): void;
}
}
String.prototype.handle = function() {
}
Compiles OK
But if I try to do the same with PromiseLike<T>
, I get a compile error '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;
}
Obviously the problem here is that PromiseLike
is generic. How can I do this properly in typescript?
Upvotes: 13
Views: 4703
Reputation: 249586
Interfaces do not exist at runtime, they are erased during compilation, so setting the value of a function on an interface is not possible. What you are probably looking for is adding the function to Promise
. You can do this similarly:
declare global {
interface Promise<T> {
handle(): Promise<T>;
}
}
Promise.prototype.handle = function<T>(this: Promise<T>): Promise<T> {
return this;
}
Upvotes: 12