Ethan Ethan - 2 months ago 19
TypeScript Question

Typing the Index Signature of a Module Namespace Object

I have a series of related classes packaged up and exported from a single module. Something like:

// states.ts

export {default as Alabama} from "./alabama";
export {default as Alaska} from "./alaska";
//...


Now, elsewhere in the code, I want to iterate over all the related classes:

import * as States from "./states.ts"

for(let stateExportName in States) {
let thisStateConstructor = States[stateExportName];
// ... do something.
}


Hold aside that iteration over a commonjs module's export names would use a for-in (like above), whereas iterating over an es6 module namespace object's exports would use a for-of (since es6 does define @@iterator on module namespace objects)... in either case, this iteration should be possible.

The problem is that, when I do
States[stateExportName]
, I get an "Index signature of object type implicitly has an 'any' type." That makes sense, since I haven't defined an index signature for the module anywhere.

My question is: is it possible to define such a signature for ES6 modules in Typescript? If so, how?

Answer

is it possible to define such a signature for ES6 modules in Typescript

No. However you can be explicit about the any nature in as shown below:

import * as States from "./states.ts"

for(let stateExportName in States) {
  let thisStateConstructor:any = States[stateExportName]; // NOTICE THE `:any`
  // ... do something.
}