【发布时间】: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