Among all the other inquiries on this topic, my issue lies with the typescript compiler seeming perplexed due to the following code snippet:
if(typeof this[method] === "function"){
await this[method](req,res,next)
}
The error message I am encountering is:
Cannot invoke an object which is possibly 'undefined'
. I had assumed that typescript would be intelligent enough to recognize when typeguards are used to avoid such errors. I've attempted using ternary operators, if(this[method]), if(this[method]!==undefined), and they all resulted in the same error.
Providing some context:
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)
}
})
}
This block represents the entirety of the issue at hand, where Method is a type defined as follows:
export type Method =
"POST" |
"GET" |
"PUT" |
"DELETE"