元素隐式具有“任何"类型,因为“窗口"类型没有索引签名? [英] Element implicitly has an 'any' type because type 'Window' has no index signature?

查看:41
本文介绍了元素隐式具有“任何"类型,因为“窗口"类型没有索引签名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Typescript 中创建一个 Factory 类,但遇到以下错误:

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

src/ts/classes/Factory.ts(8,10):错误 TS7017:元素隐式具有任何"类型,因为窗口"类型没有索引签名.

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.

以下是我的工厂类.

/**
 * @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.

推荐答案

全局window 变量是类型Window.type Window 没有 索引签名,因此,typescript 无法推断 window[yourIndex] 的类型.

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
}

请注意,这将允许在 window 上访问 any 属性,例如window.getElmentById("foo") 由于打字错误,将不再是错误.

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

旁注:从长远来看,依赖自定义修改的全局变量会带来麻烦,您也不想只为 any 键入提示.打字稿的重点是引用特定类型.any 最好永远不要使用.你不应该弄乱全局命名空间,我也建议不要依赖全局窗口变量.

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.

这篇关于元素隐式具有“任何"类型,因为“窗口"类型没有索引签名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆