Skip to content

Typing the Index Signature of a Module Namespace Object #10998

Closed
@ethanresnick

Description

@ethanresnick

Hi. 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 thisState = States[stateExportName];
  // ... do something.
}

Hold aside that iteration over a commonjs module's export names would use a for-in, 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.

I'd like to be able to provide a type for the index signature of the module namespace object, so that thisState is automatically inferred as a State. I asked on StackOverflow, and @basarat said that wasn't possible, so I'm opening an issue here for it as a potential feature request. It does seem like an edge case, so I'm not sure how worth solving it is, but it is something I bumped into.

The other thing is that, if I use the code as written above, I get an "Index signature of object type implicitly has an 'any' type" error. That makes sense, since I haven't defined an index signature for the module anywhere. However, I get that error even if I explicitly type the thisState variable as any like so:

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

I can't tell if that's a bug or expected behavior. If it is expected behavior, though, then I have to do some trickery to silence the compiler error...which is really annoying (aesthetically—but also because having any compiler errors seems to prevent tslint from running with type-checking on).

Metadata

Metadata

Assignees

No one assigned

    Labels

    Needs ProposalThis issue needs a plan that clarifies the finer details of how it could be implemented.SuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions