打字稿承诺否决类型 [英] 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.
此外,当使用此承诺时,如果我错误地使用了拒绝响应类型,我希望出现编译错误.
Moreover, when using this promise, I want to have compiling error if I use the rejection response type incorrectly.
推荐答案
如此问题, 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
拒绝承诺(这是拒绝现有promise的更好方法),而这不能通过键入系统来处理;另外, TypeScript除了 never
外,也没有异常特定的类型.
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屋!