Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

typescript

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.

like image 529
abkothman Avatar asked Feb 12 '17 21:02

abkothman


2 Answers

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

return (window as any)[className];
like image 64
Thayne Avatar answered Nov 12 '22 09:11

Thayne


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.

like image 56
k0pernikus Avatar answered Nov 12 '22 10:11

k0pernikus