首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法调用可能是'undefined‘类型的对象

无法调用可能是'undefined‘类型的对象
EN

Stack Overflow用户
提问于 2021-05-17 05:09:47
回答 1查看 95关注 0票数 0

我知道还有很多其他问题在问同样的问题,但我认为typescript编译器只是感到困惑,因为

代码语言:javascript
复制
if(typeof this[method] === "function"){
    await this[method](req,res,next)
}

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

对于上下文:

代码语言:javascript
复制
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)
        }
    })
}

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

代码语言:javascript
复制
export type Method =
    "POST" |
    "GET" |
    "PUT" |
    "DELETE"
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-05-17 05:59:08

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

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

代码语言:javascript
复制
const m = this[method];

if (typeof m === "function") {
  m(req, res, next);
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67561614

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档