Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In TypeScript how can I handle for loops when using "import * as" syntax

In TypeScript I'd like to import all modules from a file and iterate over them, but the compiler throws an error at build time. Would someone know what settings or syntax I should use to fix this?

import * as dependencies from './dependencies';

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

At build time the compiler throws the below error:

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",
    "lib": ["dom", "es2018"],
    "module": "commonjs",
    "moduleResolution": "node",
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "outDir": "./dist",
    "preserveConstEnums": true,
    "removeComments": false,
    "rootDir": "./src",
    "skipLibCheck": true,
    "sourceMap": true,
    "strict": true,
    "target": "es2018",
    "forceConsistentCasingInFileNames": true,
    "esModuleInterop": true,
    "resolveJsonModule": true,
    "isolatedModules": true
  },
  "exclude": ["node_modules"],
  "include": ["**/*.ts"]
}

EDIT:

As a workaround I'm doing something like this, but it 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]());
}
like image 885
Adam Avatar asked Feb 02 '26 19:02

Adam


1 Answers

Instead of using a for-in, try using Object.values to convert it into an Iterable/Array so you can use for-of

import * as dependencies from './dependencies';

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

or if you also need the export name, use Object.entries

import * as dependencies from './dependencies';

for (const [key, dependency] of Object.entries(dependencies)) {
  console.log(key, dependency());
}
like image 184
fregante Avatar answered Feb 04 '26 11:02

fregante