我知道还有很多其他问题在问同样的问题,但我认为typescript编译器只是感到困惑,因为
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),它们都给了我相同的错误。
对于上下文:
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)
}
})
}这是整个块,方法是具有以下定义的类型:
export type Method =
"POST" |
"GET" |
"PUT" |
"DELETE"发布于 2021-05-17 05:59:08
Typescript不能记住类型检查中的this[method]引用它被调用的this[method]。在这两种情况下,这都是一个全新的指数。这就像在没有将结果保存到变量的情况下调用数组上的.map一样-类型可能是有效的,但是没有办法使用它。
但是,一旦将索引方法分配给变量,就会记住类型检查:
const m = this[method];
if (typeof m === "function") {
m(req, res, next);
}https://stackoverflow.com/questions/67561614
复制相似问题