Ken Ken - 2 years ago 90
AngularJS Question

Iterating over module exports with implicit any

So I'm writing a module with sub-modules for angular. Notation:

module App.services {
export class SomeService { }
}


and I initialize all services using:

function defToArray(def: any): any[] {
return (def.dependencies || []).concat(def)
}

for (var s in App.services)
app.service(s, defToArray(App.services[s]));


However
defToArray(App.services[s])
causes "Index signature of object type implicitly has an 'any' type".

I already tried casting like
defToArray(<any>App.services[s])
and
defToArray(App.services[s] as any)
, but no luck.

Any thoughts?

Answer Source

Casts are not very tightly binding.

Instead of

defToArray(<any>App.services[s])

try

defToArray((<any>App.services)[s])

or if you prefer

defToArray((<{[key:string]:any}>App.services)[s])

For clarification, the goal here is not to cast the type of App.services[s], you're actually trying to provide type information for the access-by-index operator. This is only an issue when noImplicitAny is enabled (but IMO it always should be, so it's just one of the things you learn to adjust to)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download