abkothman
abkothman

Reputation: 803

Element implicitly has an 'any' type because type 'Window' has no index signature?

I'm trying to create a Factory class in Typescript, but running into the following error:

src/ts/classes/Factory.ts(8,10): error TS7017: Element implicitly has an 'any' type because type 'Window' has no index signature.

I tried searching for this error, but didn't see anything that quite matched what I'm wanting to do.

The following is my Factory class.

/**
 * @class Factory
 *
 * @description Returns object based on given class string
 */
class Factory {
    public class(className: string): any {
        return window[className];
    }
}

I would rather not just suppress implicit errors in the compiler.

Any suggestions or help would be much appreciated! If this is not the best way to go about doing this, I'm definitely open to changing it as well.

Upvotes: 69

Views: 81744

Answers (4)

Rajendra
Rajendra

Reputation: 1434

One more way to do this is:

(<any>window).className

I got this issue when using window["webkitAudioContext"] I resolved it with (<any>window).webkitAudioContext

Upvotes: 1

shuming xu
shuming xu

Reputation: 81

maybe try

return window[className as keyof WindowType];

Upvotes: 5

k0pernikus
k0pernikus

Reputation: 66519

The global window variable is of type Window. The type Window has no index signature, hence, typescript cannot infer the type of window[yourIndex].

For your code to pass, you can add this interface to a non-module file:

interface Window {
    [key:string]: any; // Add index signature
}

Note that this will allow any property access on window, e.g. window.getElmentById("foo") will stop being an error due to the typo.

Sidenote: Relying on custom modified global variables is asking for troubles in the long run, you also don't want to typehint just for any. The whole point of typescript is to reference specific types. any should at best never be used. You should not mess with the global namespace and I also advise against relying on the global window variable.

Upvotes: 58

Thayne
Thayne

Reputation: 6992

Another way to index on window, without having to add a declaration, is to cast it to type any:

return (window as any)[className];

Upvotes: 98

Related Questions