TypeScript错误:类型“ Window”上不存在属性“ X” [英] TypeScript error: Property 'X' does not exist on type 'Window'
问题描述
我已将TS添加到我的React / Redux应用程序中。
I have added TS to my React/Redux app.
我在应用程序中使用 window
对象,例如
I use window
object in my app like this:
componentDidMount() {
let FB = window.FB;
}
TS会引发错误:
TypeScript错误:类型 Window上不存在属性 FB。 TS2339
TypeScript error: Property 'FB' does not exist on type 'Window'. TS2339
我想修复该错误。
// Why doesn't this work? I have defined a type locally
type Window = {
FB: any
}
componentDidMount() {
let FB = window.FB;
}
// TypeScript error: Property 'FB' does not exist on type 'Window'. TS2339
2(修复错误)
我在这里找到了答案 https://stackoverflow.com/a/56402425/1114926
declare const window: any;
componentDidMount() {
let FB = window.FB;
}
// No errors, works well
为什么第一个版本有效,但第二个版本有效,即使我根本没有指定FB属性?
Why doesn't the first version work, but the second does, even though I do not specify FB property at all?
推荐答案
为什么声明const窗口:任何;
有效吗?
Why does declare const window: any;
work?
因为您声明了<$类型的局部变量c $ c>任何。拥有类型为 any
的东西本质上会关闭 window
的类型检查,因此您可以执行任何操作。我真的不推荐这种解决方案,这是一个非常糟糕的解决方案。
Because you declare a local variable of type any
. Having something of type any
essentially turns off type checking for window
so you can do anything with it. I really do not recommend this solution, it is a really bad one.
为什么 type Window = {FB:any}
不起作用?
您定义类型 Window
。如果在模块中定义此类型,则与全局 window
对象的类型无关,它只是碰巧称为 Window的类型
在模块中。
Why doesn't type Window = { FB: any }
work?
You define a type Window
. This type if defined in a module has nothing to do with the type of the global window
object, it is just a type that happens to be called Window
inside your module.
好的解决方案
扩展窗口
,您必须扩展全局 Window
接口。您可以这样操作:
The good solution
To extend window
you must extend the global Window
interface. You can do this like this:
declare global {
interface Window {
FB:any;
}
}
let FB = window.FB; // ok now
请注意,此扩展名将在整个项目中可用,而不仅仅是文件同样,如果 FB
有定义,您可能会考虑键入更好一些的内容( FB:typeof import('FBOrWhateverModuleNameThisHas')
)
Note that this extension is going to be available in your whole project not just the file you define it in. Also if FB
has definitions you might consider typing it a bit better (FB: typeof import('FBOrWhateverModuleNameThisHas')
)
这篇关于TypeScript错误:类型“ Window”上不存在属性“ X”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!