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 impl
maybe try
return window[className as keyof WindowType];
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.