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.
Another way to index on window, without having to add a declaration, is to cast it to type any
:
return (window as any)[className];
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With