Currently, I am developing a class that automates the creation of routes for Express and invokes a function in a controller. However, upon trying to execute this[methodName](req, res)
, I come across an error message stating: 'Element implicitly has an 'any' type because an expression of type 'string' cannot be used to index type 'AbstractActionController'. No index signature with a parameter of type 'string' was found on type 'AbstractActionController'.ts(7053).' Despite extensive research, I have yet to find a solution. I suspect that specifying types is necessary, but the method eludes me.
import AbstractActionControllerInterface from './interfaces/AbstractActionControllerInterface'
import { Application, Request, Response } from 'express'
class AbstractActionController implements AbstractActionControllerInterface {
public alias: string
private app: Application
constructor(alias: string, app: Application) {
this.alias = alias === 'index' ? '' : alias
this.app = app
this.registerActionRoutes()
}
/**
* registerActionRoutes
*
* Function to log the routes with Action indicator in a controller.
*/
private registerActionRoutes() {
const classMethods = Object.getOwnPropertyNames(
Object.getPrototypeOf(this),
)
for (const methodName of classMethods) {
if (methodName !== 'constructor' && methodName.includes('Action')) {
let route = methodName.split('Action')[0]
route = route === 'index' ? '' : route
this.app.all(
`${this.alias}/${route}`,
(req: Request, rep: Response) => {
if (typeof this[methodName] === 'function') {
this[methodName](req, rep)
}
},
)
console.log(
`[Lua]\x1b[33m Route ${this.alias}/${route} attached. \x1b[0m`,
)
}
}
}
}
export default AbstractActionController
I attempted using [key: string]: any in typing, but this lacks indexes 🤔🤔 perhaps there's knowledge I'm missing.