[英]Typescript does not allow an extended class promise to be the return type of an async function
我有一个 class 是从全局 Promise class 扩展而来的,应该有一些额外的正常和异步功能。 像“init”这样的正常功能正在工作,但像“doSomething”这样的异步功能却没有。
它总是抛出以下 typescript 错误:
异步 function 或方法的返回类型必须是全局 Promise 类型。
我不知道为什么它不起作用。 这是我正在处理的代码。
class MyPromise<T> extends Promise<T> {
private somedata = {};
constructor(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void) {
super(executor);
}
public static init<T>(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void): MyPromise<T> {
return new MyPromise(executor);
}
public async doSomething(fnc: () => Promise<number>): MyPromise<T> {
this.somedata = await fnc();
return this;
}
}
更新:@Evert 是对的,这是一个 XY 问题。
async
function 返回内置 Promise。 更改 function 的返回类型不会改变这一点。
因此,您必须将MyPromise<T>
更改为Promise<T>
,或者不使用async
。
当然你仍然可以返回 MyPromise,它只是意味着你需要停止使用 async。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.