【问题标题】:Cannot invoke an object which is possibly 'undefined' typescript无法调用可能是“未定义”打字稿的对象
【发布时间】:2021-08-06 05:43:59
【问题描述】:

我知道还有很多其他问题都在问同样的问题,但我认为打字稿编译器很困惑,因为

if(typeof this[method] === "function"){
    await this[method](req,res,next)
}

给我以下错误:Cannot invoke an object which is possibly 'undefined'。我认为 typescript 应该很聪明,因为它应该知道你是否使用 typeguard 来避免抛出这样的错误。我也尝试过三元运算符 if(this[method]), if(this[method]!==undefined),它们都给了我同样的错误。

对于上下文:

for (const type of this.types){
    const method = type.toLowerCase() as Lowercase<Method>
    this.router[method](this.renderLocation, async (req, res, next) => {
        if(typeof this[method] === "function"){
            await this[method](req,res,next)
        }
    })
}

这是整个块,Method 是具有以下定义的类型:

export type Method =
    "POST" |
    "GET" |
    "PUT" |
    "DELETE"

【问题讨论】:

    标签: typescript


    【解决方案1】:

    Typescript 无法记住类型检查中的 this[method] 是指调用它的 this[method]。在这两种情况下,它都是一个全新的索引。这就像在数组上调用 .map 而不将结果保存到变量 - 类型可能有效但无法使用它。

    但是,一旦将索引方法分配给变量,就会记住类型检查:

    const m = this[method];
    
    if (typeof m === "function") {
      m(req, res, next);
    }
    

    【讨论】:

    • 非常感谢这个工作,没想到是这样。现在想来,确实有道理。
    猜你喜欢
    • 2019-07-30
    • 2019-09-15
    • 1970-01-01
    • 2021-01-19
    • 2019-12-24
    • 1970-01-01
    • 2021-08-24
    • 2020-10-02
    • 2021-12-17
    相关资源
    最近更新 更多