打字稿承诺拒绝类型 [英] Typescript Promise rejection type
问题描述
如何设置拒绝我的承诺的类型?假设我愿意:
How do I set the type of the rejection of my promise? Let's say I do:
const start = (): Promise<string> => {
return new Promise((resolve, reject) => {
if (someCondition) {
resolve('correct!');
} else {
reject(-1);
}
});
}
假设我想用一个数字拒绝.但是我不能设置类型;我可以将任何我想要的传递给 reject
在这里.
Let's say I want to reject with a number. But I cannot set the type; I can pass whatever I want to the reject
here.
而且,在使用这个promise的时候,如果我错误地使用了拒绝响应类型,我希望有编译错误.
Moreover, when using this promise, I want to have compiling error if I use the rejection response type incorrectly.
推荐答案
如 this issue, Promise
对于已完成和被拒绝的承诺没有不同的类型.拒绝
接受不影响承诺类型的任何
参数.
As explained in this issue, Promise
doesn't have different types for fulfilled and rejected promises. reject
accepts any
argument that doesn't affect type of a promise.
目前 Promise
不能更好地输入.这是因为可以通过在 then
或 catch
中 throw
ing 来拒绝承诺(这是拒绝现有承诺的更好方法), 这不能通过打字系统来处理;此外,除了never
之外,TypeScript 也没有特定于异常的类型.
Currently Promise
cannot be typed any better. This results from the fact that a promise can be rejected by throw
ing inside then
or catch
(this is a preferable way to reject existing promise), and this cannot be handled by typing system; also, TypeScript also doesn't have exception-specific types except never
.
这篇关于打字稿承诺拒绝类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!