无法调用可能是“未定义”打字稿的对象

时间:2021-05-16 21:09:46

标签: typescript

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

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

给我以下错误:Cannot invoke an object which is possibly 'undefined'。我认为 typescript 应该很聪明,因为它应该知道您是否使用 typeguards 不会抛出这样的错误。我也试过三元运算符 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"

1 个答案:

答案 0 :(得分:1)

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

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

const m = this[method];

if (typeof m === "function") {
  m(req, res, next);
}