How do I manage 'for' loops in TypeScript while using the 'import * as' syntax?

When working with TypeScript, I encountered an issue while trying to import and iterate over all modules from a file. The compiler throws an error at build time. Can anyone help me figure out the correct settings or syntax to resolve this?

import * as dependencies from './dependencies';

for (const key in dependencies) {
  console.log(dependencies[key]());
}

The compiler produces the following error during build:

error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof import("/src/dependencies/index")'.
  No index signature with a parameter of type 'string' was found on type 'typeof import("/src/dependencies/index")'. 

tsconfig.json

{
   "compilerOptions": {
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "jsx": "react",
    ...
    ... [configuration details]
    ...
    "isolatedModules": true
  },
  "exclude": ["node_modules"],
  "include": ["**/*.ts"]
}

EDIT:

To work around this issue, I'm implementing the following workaround which seems redundant.

import * as dependencies from './dependencies';

interface Collection {
  [key: string]: any;
}

const dependencyCollection: Collection = dependencies;

for (const key in dependencyCollection) {
  console.log(dependencyCollection[key]());
}

Answer №1

Instead of using a standard for loop, consider utilizing Object.values to transform it into an Iterable/Array which can then be iterated over with a for-of loop

import * as dependencies from './dependencies';

for (const dependency of Object.values(dependencies)) {
  console.log(dependency());
}

If you require both the export name and the value, you can use Object.entries instead

import * as dependencies from './dependencies';

for (const [key, dependency] of Object.entries(dependencies)) {
  console.log(key, dependency());
}

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

NextAuth credentials are undefined and authentication is malfunctioning in React

I encountered the following issue: This is the code snippet that I am using: return ( <> {Object.values(providers).map((provider) => { if (provider.id === "credentials") { return null; } retu ...

TypeORM is failing to create a table upon initialization

Recently, I delved into the realm of typescript and decided to explore TypeORM for backend development. My current project involves building a CRUD API using typeORM and postgreSQL. After configuring everything initially, I ran the application only to rea ...

Having trouble retrieving a value from a reference object in React Typescript?

Struggling with a login form issue in my React TypeScript project. Below is the code for the react login form: login-form.tsx import * as React from 'react'; import { Button, FormGroup, Input, Label } from 'reactstrap' ...

Canceling a promise in a Vuex action

I am looking to implement the ability to cancel a running promise in my Vue component, specifically a promise returned by a Vuex action. In my scenario, the Vuex action is continuously polling an endpoint for status updates, and I need the capability to s ...

Having trouble getting @types/express-session to function properly. Any suggestions on how to fix it?

My web-app backend is built with TypeScript and I've integrated express-session. Despite having @types/express and @types/express-session, I continue to encounter type errors that say: Property 'session' does not exist on type 'Request ...

JavaScript's Array.map function failing to return a value

Here is a snippet of code from an api endpoint in nextJS that retrieves the corresponding authors for a given array of posts. Each post in the array contains an "authorId" key. The initial approach did not yield the expected results: const users = posts.ma ...

Adding ngrx action class to reducer registration

Looking to transition my ngrx actions from createAction to a class-based approach, but encountering an error in the declaration of the action within the associated reducer: export enum ActionTypes { LOAD_PRODUCTS_FROM_API = '[Products] Load Products ...

Angular 16 SSR encounters a TypeError when the 'instanceof' operator is used on a value that is not an object

I have been facing an issue while updating my Angular application from version 15 to 16. Everything seems to work fine with Angular, including building for Angular Universal without any errors. However, when I attempt to serve using npm run serve:ssr, it t ...

Encountering an issue with importing JSON in Python resulting in a BadStatus

Currently, I am attempting to import the Json data that is being generated by an Impinj R420 reader. Here is the code snippet that I have been using: # Importing the necessary libraries import urllib.request from urllib.request import urlopen import json ...

The inference of optional generic types is not occurring

I need help addressing a type error in my TypeScript wrapper for handling NextJS API requests. Specifically, I am facing an issue when trying to pass a single type for one of the generic types in the function. To illustrate this error, I have created a si ...

Is there a way to verify the availability of an authenticated resource without triggering a pop-up for credentials in the browser?

I am facing the challenge of fetching data from a web service located on a different server without knowing if the user has an active session on that server. If the user does have a session, I want to retrieve the data automatically. However, if they do no ...

Adjust the size and color of text in Chart.js using Angular 5

Why does the font color in chartjs appear as light gray and not print when you want to do so from the page? I tried changing the font color of chartjs in the options attribute, but it didn't work. How can I change the font color in chartjs angular? ...

calculate the difference between two dates and then add this difference to a new date

Utilizing TypeScript for date calculations. Example: Initial Date 1: "10/06/2021 10:10:05" Initial Date 2: "08/06/2021 11:10:05" Calculate the difference between the two dates, including date/month/year/hour/min/sec/milliseconds. Ensure compatibility wi ...

The attribute 'pixiOverlay' is not found in the property

Working on my Angular 8 project, I needed to display several markers on a map, so I chose to utilize Leaflet. Since there were potentially thousands of markers involved, I opted for Leaflet.PixiOverlay to ensure smooth performance. After installing and imp ...

The issue with launching a Node.js server in a production environment

I'm currently facing an issue when trying to start my TypeScript app after transpiling it to JavaScript. Here is my tsconfig: { "compilerOptions": { "module": "NodeNext", "moduleResolution": "NodeNext", "baseUrl": "src", "target": " ...

Please come back after signing up. The type 'Subscription' is lacking the specified attributes

Requesting response data from an Angular service: books: BookModel[] = []; constructor(private bookService: BookService) { } ngOnInit() { this.books = this.fetchBooks(); } fetchBooks(): BookModel[] { return this.bookService.getByCategoryId(1).s ...

Using masonry-layout with Next Js leads to a ReferenceError stating that window is not defined

Implementing the masonry-layout library by David Desandro in my Next app has been a smooth process. You can find the link here. When I apply it, the masonry layout functions perfectly as intended. Here's how I'm incorporating it successfully: imp ...

What is the name of the file that contains a class?

I am curious about identifying the file that called a specific class: database.ts class Database { constructor() { console.log(`I want to know who called this class`); } } server.ts import Database from 'database.ts'; new Databa ...

Retrieve the TaskID of an ECS Fargate container for exporting and future use within AWS CDK code

Currently, I am leveraging CDK version 2 alongside Typescript. In my current setup, I encounter a situation where I necessitate the TaskID value from ECS Fargate Container to be incorporated into another command. The process involves me utilizing new ecs ...

What advantages could learning ReactJS first give me before diving into NextJS?

Just mastered TS and now faced with the decision of choosing a framework. I'm curious why it's recommended to learn ReactJS before NextJS. I've read countless articles advising this, but no one seems to delve into the reasons behind it. Ca ...