子类重写Promise的then方法返回super时出现类型不兼容问题
问题原因与解决方案
你遇到的问题出在TypeScript对泛型方法类型推断的处理上。你用Parameters<InstanceType<typeof Promise<T>>["then"]>获取参数类型时,没有保留原Promise.then方法的泛型特性——原then方法是泛型方法,它接收两个可选回调,分别对应成功和失败的结果类型TResult1、TResult2,而你的写法里TypeScript会把这两个泛型参数默认推断为unknown,导致你的then方法返回值被推断为Promise<unknown>,但基类Promise<T>的then方法返回的是Promise<TResult1 | TResult2>,类型不匹配,所以报错。
正确的写法是让你的ExtendedPromise的then方法和基类保持一致的泛型定义,明确指定泛型参数,这样参数和返回值类型就能完全对齐:
class ExtendedPromise<T> extends Promise<T> { then<TResult1 = T, TResult2 = never>( onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null | undefined ): Promise<TResult1 | TResult2> { console.log("Do something here"); return super.then(onfulfilled, onrejected); } }
或者你也可以用Parameters结合泛型的方式,避免重复写参数类型:
class ExtendedPromise<T> extends Promise<T> { then<TResult1 = T, TResult2 = never>( ...args: Parameters<Promise<T>["then"]<TResult1, TResult2>> ): Promise<TResult1 | TResult2> { console.log("Do something here"); return super.then(...args); } }
这样写的核心是保留then方法的泛型参数TResult1和TResult2,让TypeScript能根据传入的回调推断出正确的返回值类型,和基类的then方法类型完全匹配,就不会出现类型不兼容的错误了。
内容的提问来源于stack exchange,提问作者mt_xing
相关产品推荐
相关产品推荐

