typescript - 如何实现 PromiseLike 接口?
问题描述
我尝试使用 thenable 支持实现自动提交过程。但我无法绕过上次抱怨的类型错误:
type JobResolve = () => void
export class Job implements PromiseLike<JobResolve> {
public then<TResult1 = JobResolve>(onfulfilled?: ((value: JobResolve) => (PromiseLike<TResult1> | TResult1)) | undefined | null): PromiseLike<TResult1> {
const done = () => {}
if (typeof onfulfilled === 'function') {
const thenable = Promise.resolve(onfulfilled(done))
done()
return thenable
} else {
// Error here!
// TS2322: '() => void' is assignable to the constraint of type 'TResult1', but 'TResult1' could be instantiated with a different subtype of constraint '{}'.
return Promise.resolve(done)
}
}
}
如何解决?(没有Promise.resolve(done as any)
)
解决方案
您的else
分支在PromiseLike
. 考虑这个例子。
async function f() {
let t: {a: string} = await Promise.resolve(1).then<{a: string}>();
console.log(t, t.a, typeof t, typeof t.a);
}
f();
t
是number
not类型object
,但类型系统认为它是一个对象。
如果您的目标是提供与 的合规性Promise
,那么您不妨将返回值转换为返回类型,如下所示:
return Promise.resolve(done) as PromiseLike<TResult1>
或者,为了更安全,抛出异常。
推荐阅读
- java - Spark 按日期分组数据和该日期缺少的 id 的零填充数据
- automated-tests - 我们应该如何在 Docker 容器中测试我们的应用程序?
- mysql - 根据条件将查询的数据组合成一行
- c# - Xamarin Android c# Viewstub 只工作一次,然后获取空指针
- arrays - Ruby - 将数组转换为哈希
- android - Android库重复条目:okio/AsyncTimeout$1.class
- vba - 从范围中分离列
- linux - 通过 docker 容器中的 -e 标志传递的环境变量在入口点脚本中不可访问
- linux - 为什么 mmap 值的物理地址为零?
- python - Python-celery(v4.1.0) beat 任务运行失败,参数号错误