TypeScript,找不到 if else 内声明的名称

fro*_*uma 3 node.js typescript

if (!challengeType) {
   const { brawl, fight }: any = await userModel
                                          .findOneAndUpdate(
                                               { _id: req.userData._id },
                                               { $inc: { 'fight.remaining': -1 } },
                                               { 'new': true }
                                           )
} else {
   const { brawl, fight }: any = await userModel
                                          .findOneAndUpdate(
                                               { _id: req.userData._id },
                                               { $inc: { 'brawl.remaining': -1 } },
                                               { 'new': true }
                                          )
}

// typescript error here
// "Cannot find name brawl", and "Cannot find name fight"

console.log(brawl, fight)
Run Code Online (Sandbox Code Playgroud)

不知道为什么打字稿找不到名字 brawl 和打架,这可能是打字稿在 if else 语句的情况下错误处理的问题,

但如果脚本正在运行,则不会出现问题。

jfr*_*d00 5

constlet是块作用域,因此它们在比声明它们​​的块更高的作用域中不可用。您试图在声明它们的块之外访问它们。您可以在let更高的作用域中声明它们。

let result: any;
if (!challengeType) {
   result = await userModel.findOneAndUpdate(
           { _id: req.userData._id },
           { $inc: { 'fight.remaining': -1 } },
           { 'new': true });
} else {
   result = await userModel.findOneAndUpdate(
           { _id: req.userData._id },
           { $inc: { 'brawl.remaining': -1 } },
           { 'new': true });
}

// typescript error here
// "Cannot find name brawl", and "Cannot find name fight"
const { brawl, fight } = result;
console.log(brawl, fight);
Run Code Online (Sandbox Code Playgroud)

您可能需要修复一些 TypeScript 语法,因为我不太了解 TypeScript,但您应该在这里了解总体思路。


实际上,您可以稍微干燥一下并删除一堆重复的代码。

const queryType: string = challengeType ? 'brawl' : 'fight';
const { brawl, fight }: any = await userModel.findOneAndUpdate(
                              { _id: req.userData._id },
                              { $inc: { [`${queryType}.remaining`]: -1 } },
                              { 'new': true });
console.log(brawl, fight);
Run Code Online (Sandbox Code Playgroud)

不知道为什么打字稿找不到名字争吵和打斗

因为您试图在声明它们的范围之外访问这些变量。ifor的主体else是一个单独的块作用域,并且 和letconst仅在该作用域内可用(注意var是函数作用域,而不是块作用域)。

在 if else 语句的情况下,这可能是打字稿错误处理的问题,

不,这不是打字稿问题。这就是语言的设计方式。限制变量的访问范围是该语言的一个特性。Javascript 在这方面也是如此。