gpt4 book ai didi

javascript - typescript :为 promise 中的解析参数指定正确的返回类型

转载 作者:行者123 更新时间:2023-11-30 14:07:08 25 4
gpt4 key购买 nike

昨天,我决定尝试使用 typescript 并尝试将一些基本的 javascript promise 示例移植到 typescript promise。但是,在移植示例的过程中,我遇到了一个我仍然无法弄清楚的问题。尝试用谷歌搜索也没用。

场景:我确实有一个返回 Promise 的函数,该函数在执行时解析为 number。我还想在此示例中测试一些 then 场景。

请在下面找到代码示例:

function test_promise(): Promise<number>{
return new Promise((resolve, reject) :number => {
let result:number = 10;
resolve(result);
}).then(result => { // first then
console.log("Result: " + (typeof result)); // Result: number
return result * 2; //
}).then(result => { // second then
return result * 2;
}).then(result => { // third then
return result * 2;
});
}

为了更清楚起见,我还添加了两个屏幕截图。

屏幕截图 1:

enter image description here

截图2

enter image description here

目前有几件事我不清楚:

  1. 在屏幕截图 1 中,提示项并未说明 typeof 结果为 number,但在 console.log 中打印时,它说这是一个 number。有什么区别?
  2. 如果它在控制台中打印出它是一个数字,那么为什么它不允许我对其执行乘法运算。

我需要在此处更改什么才能使此示例正常工作?

请你们给它一些启发。谢谢。

问候,

最佳答案

这里的解决方案是显式指定第一个Promise的值类型通过添加 <number> 实例化的对象直接在 new Promise 之后如图:

    /* Add <number> after new Promise */
return new Promise<number>((resolve, reject) => {
let result:number = 10;
resolve(result);
}).then(result => { // first then
console.log("Result: " + (typeof result)); // Result: number
return result * 2; //
}).then(result => { // second then
return result * 2;
}).then(result => { // third then
return result * 2;
});

这样做会通知 Typescript 第一个 promises 值类型,这允许推断链中后续 promises 的值类型。

这将反过来解决您的问题。有关 Generics in Typescript can be found here 的更多信息.希望对您有所帮助!

关于javascript - typescript :为 promise 中的解析参数指定正确的返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55159371/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com