typescript 打字稿错误:“窗口”类型上不存在属性“X”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/56457935/
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
TypeScript error: Property 'X' does not exist on type 'Window'
提问by Green
I have added TS to my React/Redux app.
我已将 TS 添加到我的 React/Redux 应用程序中。
I use window
object in my app like this:
我window
在我的应用程序中使用对象是这样的:
componentDidMount() {
let FB = window.FB;
}
TS throws an error:
TS 抛出错误:
TypeScript error: Property 'FB' does not exist on type 'Window'. TS2339
TypeScript 错误:“窗口”类型上不存在属性“FB”。TS2339
I want to fix the error.
我想修复错误。
1 (doesn't work)
1(不起作用)
// 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 (fixes the error)
2(修复错误)
I found the answer here https://stackoverflow.com/a/56402425/1114926
我在这里找到了答案https://stackoverflow.com/a/56402425/1114926
declare const window: any;
componentDidMount() {
let FB = window.FB;
}
// No errors, works well
Why doesn't the first version work, but the second does, even though I do not specify FB property at all?
为什么第一个版本不起作用,但第二个版本起作用,即使我根本没有指定 FB 属性?
回答by Titian Cernicova-Dragomir
Why does declare const window: any;
?
为什么declare const window: any;
?
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.
因为您声明了一个类型为 的局部变量any
。拥有某种类型any
本质上会关闭类型检查,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.
为什么不起作用type Window = { FB: any }
?您定义一个类型Window
。这种类型如果在模块中定义,则与全局window
对象的类型无关,它只是Window
在模块内部调用的类型。
The good solutionTo extend window
you must extend the global Window
interface. You can do this like this:
好的解决方案要扩展,window
您必须扩展全局Window
接口。你可以这样做:
declare global {
interface Window {
FB:any;
}
}
let FB = window.FB; // ok now
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')
)
请注意,此扩展将在您的整个项目中可用,而不仅仅是您定义它的文件。此外,如果FB
有定义,您可能会考虑更好地输入它 ( FB: typeof import('FBOrWhateverModuleNameThisHas')
)