gpt4 book ai didi

typescript - 如何在 typescript 中将方法添加到泛型类的原型(prototype)

转载 作者:搜寻专家 更新时间:2023-10-30 21:06:24 25 4
gpt4 key购买 nike

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

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

String.prototype.handle = function() {
}

编译成功

但是如果我尝试对 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是通用的。我怎样才能在 typescript 中正确地做到这一点?

最佳答案

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

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

Promise.prototype.handle = function<T>(this: Promise<T>): Promise<T> {
return this;
}

关于typescript - 如何在 typescript 中将方法添加到泛型类的原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52514013/

25 4 0
文章推荐: typescript - Angular 6 Reactive Forms - 根据条件动态设置