Typed Promise在添加' finally '时将返回类型更改为unknown



我有一个静态类型返回类型的常规承诺:

export const hasActiveSubscription = (whatEver: string): Promise<string> => 
new Promise((resolve, reject) => {
if (true){
return resolve('imastring')
}
return reject(new Error('nope'))
})

到目前为止都很好,但是如果我添加一个finally块,它将返回类型更改为unknown,并且无法传递该字符串类型,例如

export const hasActiveSubscription = (whatEver: string): Promise<string> => 
new Promise((resolve, reject) => {
if (true){
resolve('imastring')
}
reject(new Error('nope'))
}).finally(console.info)

类型'Promise'不能赋值给类型'Promise'。
类型'unknown'不能赋值给类型'string'。

我如何在保留finally块的同时保留原始返回类型?

如果它有帮助,我的实际代码有一个setTimeout(以确保这个函数不会花太长时间返回),我想清除超时最后,而不是清除超时在5个不同的位置。

如果您从函数签名的返回位置删除类型注释,您将注意到实际的返回类型是Promise<unknown>,而不是您所期望的Promise<string>,这构成了错误的第一部分:

const hasActiveSubscription: (whatEver: string) => Promise<unknown>;

Promise是一个泛型接口,它的finally方法在其返回类型注释中使用接口的类型参数(示例来自ES2018库):

interface Promise<T> {
finally(onfinally?: (() => void) | undefined | null): Promise<T>
}

你所需要做的就是指定构造的Promise的类型,然后一切都会好起来:

export const hasActiveSubscription = (whatEver: string) => 
new Promise<string>((resolve, reject) => {
if (true){
resolve('imastring')
}
reject(new Error('nope'))
}).finally(console.info) //no error, Promise<string> is inferred

游乐场


小提示-您的示例在reject调用

中有一个不匹配的括号

最新更新