加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Windows > 正文

typescript – Element隐式具有’any’类型,因为类型’Window’

发布时间:2020-12-13 20:48:37 所属栏目:Windows 来源:网络整理
导读:我正在尝试在Typescript中创建一个Factory类,但遇到以下错误: src/ts/classes/Factory.ts(8,10): error TS7017: Element implicitly has an ‘any’ type because type ‘Window’ has no index signature. 我试图搜索这个错误,但没有看到任何与我想要做
我正在尝试在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;
}

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读