Currently, I am facing a challenge in my project where I am dynamically generating routes and managing them in an Elysia(~Express) application. The issue arises when TypeScript's type checking system fails to index an object using a string variable. Setting the app:any
seems like a workaround, but it defeats the purpose.
//server.tsx
function createRoutes(path: string) {
const routes = readdirSync(path);
routes.forEach(async (route) => {
const dirPath = `${path}/${route}`;
const isDir = statSync(dirPath).isDirectory();
if (isDir) {
createRoutes(dirPath);
const routePath = dirPath.split(`src/pages/`)[1];
const filePath = `./src/pages/${routePath}`;
let fileName: string = readdirSync(dirPath)
.filter((file) => statSync(`${dirPath}/${file}`).isFile())
.map((file) => basename(file).split(".")[0])[0];
if (fileName == `page`) {
const componentName =
route.charAt(0).toUpperCase() + route.slice(1);
const componentPath = `${filePath}/page`;
app.get(routePath, async ({ headers, html }: any) => {
const { [componentName]: Component } = await import(
componentPath
);
return html(sendPage(headers, Component));
});
} else if (fileName == `route`) {
const apiPath = `${filePath}/route`;
const route = await import(apiPath);
for (const fun in route) {
app[fun](routePath, () => route[fun]());//<= error
}
}
}
});
}
///route.tsx
let message = `hi mom`;
export async function get() {
return message;
}
export async function post() {
return message;
}
export async function patch() {
return message;
}
//error
[{
"resource": "/d:/Projects/Web Dev/Learning/fireBEH/server.tsx",
"owner": "typescript",
"code": "7053",
"severity": 8,
"message": "Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Elysia<\"\", { request: {}; store: {}; schema: {}; error: {}; meta: { defs: {}; exposed: {}; schema: { \"/\": { get: { body: unknown; headers: undefined; query: undefined; params: undefined; response: { '200': Promise<any>; }; }; }; }; }; }>'.\n No index signature with a parameter of type 'string' was found on type 'Elysia<\"\", { request: {}; store: {}; schema: {}; error: {}; meta: { defs: {}; exposed: {}; schema: { \"/\": { get: { body: unknown; headers: undefined; query: undefined; params: undefined; response: { '200': Promise<any>; }; }; }; }; }; }>'.",
"source": "ts",
"startLineNumber": 73,
"startColumn": 21,
"endLineNumber": 73,
"endColumn": 29
}]