typescript – Element隐式具有’any’类型,因为类型’Window’没有索引签名?

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

src/ts/classes/Factory.ts(8,10): error TS7017: Element implicitly has an ‘any’ type because type ‘Window’ has no index signature.

我试图搜索这个错误,但没有看到任何与我想要做的完全匹配的东西。

以下是我的Factory类。

/**
 * @class Factory
 *
 * @description Returns object based on given class string
 */
class Factory {
    public class(className: string): any {
        return window[className];
    }
}

我宁愿不仅仅是抑制编译器中的隐式错误。

任何建议或帮助将不胜感激!如果这不是最好的方法,我肯定愿意改变它。

全局窗口变量的类型为Window。类型Window没有 index signature,因此,typescript无法推断窗口的类型[yourIndex]。

Window的定义来自typescript’s lib.d.ts

declare var Window: {
    prototype: Window;
    new(): Window;
}

为了让您的代码通过,您需要以下内容:

declare var Window: {
    [key:string]: any; // missing index defintion
    prototype: Window;
    new(): Window;
}

旁注:从长远来看,依赖于自定义修改的全局变量是一个问题,你也不想只为任何变量提示。打字稿的重点是引用特定的类型。任何人都应该永远不会被使用。你不应该搞乱全局命名空间,我也建议不要依赖全局窗口变量。

相关文章

文章浏览阅读2.2k次,点赞6次,收藏20次。在我们平时办公工作...
文章浏览阅读1k次。解决 Windows make command not found 和...
文章浏览阅读3.2k次,点赞2次,收藏6次。2、鼠标依次点击“计...
文章浏览阅读1.3w次。蓝光版属于高清版的一种。BD英文全名是...
文章浏览阅读974次,点赞7次,收藏8次。提供了更强大的功能,...
文章浏览阅读1.4w次,点赞5次,收藏22次。如果使用iterator的...