如何在打字稿中向泛型类的原型添加方法

Arc*_*heg 7 typescript

我正在尝试向PromiseLike<T> With的原型添加一个方法,String这不是问题:

declare global {
    interface String {
        handle(): void;
    }
}

String.prototype.handle = function() {
}
Run Code Online (Sandbox Code Playgroud)

编译正常

但是,如果我尝试对 执行相同操作,则会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;
}
Run Code Online (Sandbox Code Playgroud)

显然,这里的问题PromiseLike是通用的。我怎样才能在打字稿中正确地做到这一点?

Tit*_*mir 9

接口在运行时不存在,它们在编译期间会被擦除,因此无法在接口上设置函数的值。您可能正在寻找的是将函数添加到Promise. 您可以类似地执行此操作:

declare global {
  interface Promise<T> {
      handle(): Promise<T>;
  }
}

Promise.prototype.handle = function<T>(this: Promise<T>): Promise<T> {
  return this;
}
Run Code Online (Sandbox Code Playgroud)

  • @samvv `this` 参数在编译期间被取出,所以在运行时上面的函数没有参数。 (2认同)