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

后端 未结 3 1107
情歌与酒
情歌与酒 2020-12-05 22:15

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

相关标签:
3条回答
  • 2020-12-05 23:00

    maybe try

    return window[className as keyof WindowType];

    0 讨论(0)
  • 2020-12-05 23:11

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

    return (window as any)[className];
    
    0 讨论(0)
  • 2020-12-05 23:12

    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.

    0 讨论(0)
提交回复
热议问题