I'm trying to dynamically add routes to my api by iterating over an array of objects called route groups. A route group can have many routes.
Here are my types (the RouterContext type comes from Oak middleware framework):
// routes/mod.ts
type Route = {
method: string;
path: string;
handler: (ctx: RouterContext) => Promise<void>;
};
export type RouteGroup = {
group: {
prefix: string;
};
routes: Route[];
};
Here is my router class:
export class Router {
// imported Oak's Router class as oakRouter
router: oakRouter;
constructor() {
this.router = new oakRouter({ prefix: "/api" });
}
register(): void {
this._createRoutes(routeGroups);
}
private _createRoutes(routeGroups: RouteGroup[]) {
routeGroups.forEach(({ group, routes }) => {
routes.forEach(({ method, path, handler }) => {
this.router[method](group.prefix + path, handler); // <-- this.router[method] is underlined with an error
});
});
}
}
A typical route looks like this:
router.get("/", (ctx) => {
ctx.response.body = "Welcome to My Oak App.";
});
But when I use bracket notation to dynamically add the http method that I want to use in _createRoutes(), I get the following error:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Router<RouteParams, Record<string, any>>'.
No index signature with a parameter of type 'string' was found on type 'Router<RouteParams, Record<string, any>>'.deno-ts(7053)
How do I change the method property on the Route type from a string into a valid index signature? Is that even what I need to do?