Error in TypeScript when accessing object using string variable as index

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
}]

Answer №1

Have you taken the necessary steps to install the types? ➡️ npm i @types/express or yarn add @types/express This process is typically required for frameworks/libraries other than express.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discover a more efficient method for expanding multiple interfaces

Hey there, I'm having some trouble with TypeScript and generics. Is there a better way to structure the following code for optimal cleanliness and efficiency? export interface Fruit { colour: string; age: number; edible: boolean; } export inte ...

Why will the experimental activation of React concurrent features in Nextjs 12 disable API routes?

I just upgraded to Next.js version 12 and set up some API routes (e.g. "/api/products"). These routes were functioning properly, but when I enabled concurrentFeatures: true in my next.config.ts, the API routes stopped working. The console display ...

Unidentified Controller Scope in Angular and TypeScript

I am struggling with my Angular 1.5 app that uses Typescript. Here is a snippet of my code: mymodule.module.ts: angular.module('mymodule', []).component('mycomponent', new MyComponent()); mycomponent.component.ts export class MyCont ...

Here is a guide on showcasing information obtained from ASP.NET API in Angular version 13

My goal is to fetch motorcycle data from a web API and showcase it in my Angular project. ASP.NET Framework Web API 4.7 Angular CLI: 13.3.7 Angular: 13.3.11 On the Web API end: Controller: [EnableCors(origins: "*", headers: "*", ...

What exactly are the implications of having dual type declarations in TypeScript?

I recently came across the Angular tutorial here In the code snippet below, there are double type declarations that I am having trouble understanding. handleError<T>(operation = 'operation', result?: T) { return (error: any): Observabl ...

Karma Error: Unexpected token import in Angular 2 - Uncovering a Syntax Error

I've been exploring this insightful tutorial on https://www.youtube.com/watch?v=yG4FH60fhUE and also referencing https://angular.io/docs/ts/latest/guide/testing.html to create basic unit tests in Angular 2 and ensure the proper setup of Karma. I encou ...

When viewing an array, the objects' values are displayed clearly; however, when attempting to access a specific value, it

I am attempting to retrieve the board_id of my objects in the columnsServer array... columnsServer: Column[]; this.service.getColumns() .subscribe(data => { this.columnsServer = data; console.log(this.columnsServer); for (this.i = 0; this.i ...

Tips for formatting Express API responses in an organized fashion

I'm seeking assistance with my Express API endpoint. I want the user details response to be customized in a specific structure, like so: { "userId": "a38a8320-b750-41d1-a2d3-117dd286eeb5", //guid "firstName": "John ...

Using TypeScript to create a generic function that returns a null value

In my Typescript code, I have the following function: In C#, you can use default(T), but I'm not sure what the equivalent is in Typescript. public Base { ... } public Get<T extends Base>(cultura: string): T[] { let res = null; try ...

After importing this variable into index.ts, how is it possible for it to possess a function named `listen`?

Running a Github repository that I stumbled upon. Regarding the line import server from './server' - how does this API recognize that the server object has a method called listen? When examining the server.ts file in the same directory, there is ...

Initiating an AJAX request to communicate with a Node.js server

Recently, I started exploring NodeJS and decided to utilize the npm spotcrime package for retrieving crime data based on user input location through an ajax call triggered by a button click. The npm documentation provides the following code snippet for usi ...

What could be the reason for the cookie not being set in express?

I have been using Node.js with Express for my server-side and React for client-side development. Everything was working fine until recently when I encountered an issue with saving tokens in signed cookies. This problem is happening both in my development e ...

The ng-model used within an *ngFor loop is not displaying the correct value

I am working with a JSON file in my Angular2 App. The specific JSON object I am referring to is named tempPromotion and I am trying to access the data within ['results'] like this: tempPromotion['response_payload']['ruleset_list ...

Issue with Ionic2 radio button selection not persisting

I'm currently working on implementing Radio Alerts within an Ionic2 application. To create a radio alert, I used the following code snippet: let alert = this.alertCtrl.create(); alert.setTitle('Select a Radio Alert'); alert.addInput({ typ ...

Stop the print dialog box from appearing when using the Ctrl + P shortcut

I'm working on an Angular app and I want to prevent the print dialog from opening when pressing "Ctrl + P". To address this issue, I have implemented the following code: window.onbeforeprint = (event) => { event.stopPropagation(); cons ...

Exploring the Power of SectionList in Typescript

How should SectionList be properly typed? I am encountering an issue where this code works (taken from the official documentation example): <SectionList renderItem={({item, index}) => <Text key={index}>{item}</Text>} renderSectionHea ...

How can I postpone the initialization of ngOnInit in Angular 7?

While attempting to send and retrieve data for display, I encountered an issue where the component initializes before the new data is added to the server. This results in a missing element being displayed. Is there a way to delay the initialization proce ...

Testing React components with React Testing Library and Effector (state manager) made easy

I am currently utilizing effector along with React Testing Library (RTL). While going through the RTL documentation, I came across an interesting article regarding the usage of customerRender, where we provide AllTheProviders as a wrapper for the render fu ...

A Promise is automatically returned by async functions

async saveUserToDatabase(userData: IUser): Promise<User | null> { const { username, role, password, email } = userData; const newUser = new User(); newUser.username = username; newUser.role = role; newUser.pass ...

Error: Missing npm install -g @angular/cli@latest package in devDependencies section

ng build is causing an issue that The error reads: Unable to Find npm install -g @angular/cli@latest in devDependencies. When I attempt to start the application using npm start, it works fine. However, while trying to build a file, I encounter this er ...