typescript 元素隐式具有“任何”类型,因为“窗口”类型没有索引签名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42193262/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Element implicitly has an 'any' type because type 'Window' has no index signature?
提问by abkothman
I'm trying to create a Factory class in Typescript, but running into the following error:
我正在尝试在 Typescript 中创建一个 Factory 类,但遇到以下错误:
src/ts/classes/Factory.ts(8,10): error TS7017: Element implicitly has an 'any' type because type 'Window' has no index signature.
src/ts/classes/Factory.ts(8,10): 错误 TS7017: 元素隐式具有 'any' 类型,因为类型 'Window' 没有索引签名。
I tried searching for this error, but didn't see anything that quite matched what I'm wanting to do.
我尝试搜索此错误,但没有看到与我想要做的完全匹配的任何内容。
The following is my Factory class.
以下是我的工厂类。
/**
* @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.
任何建议或帮助将不胜感激!如果这不是执行此操作的最佳方式,我也绝对愿意更改它。
采纳答案by k0pernikus
The global window
variable is of type Window
. The type Window
has no index signature, hence, typescript cannot infer the type of window[yourIndex]
.
全局window
变量是type Window
。在type Window
没有指数的签名,因此,打字稿不能推断的类型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 anyproperty access on window
, e.g. window.getElmentById("foo")
will stop being an error due to the typo.
请注意,这将允许对 的任何属性访问window
,例如,window.getElmentById("foo")
由于拼写错误,将不再是错误。
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.
旁注:从长远来看,依赖自定义修改的全局变量会带来麻烦,您也不想只为any
. 打字稿的重点是引用特定类型。any
最好永远不要使用。你不应该弄乱全局命名空间,我也建议不要依赖全局窗口变量。
回答by Thayne
Another way to index on window, without having to add a declaration, is to cast it to type any
:
无需添加声明即可在 window 上建立索引的另一种方法是将其强制转换为 type any
:
return (window as any)[className];
回答by shuming xu
maybe try
也许试试
return window[className as keyof WindowType];
return window[className as keyof WindowType];