英文:
How to use external namespaces for types in TypeScript / TSX
问题
// 这里对 window.FB 进行了类型定义
const fb = new Facebook(window.FB)
class Facebook {
// 在这里如何给 fb 添加类型?
constructor(fb) {
this.fb = fb
}
有没有办法使用命名空间获取类型?在这种情况下,是否需要自己编写类型?期待您的建议!
英文:
I'm working with some scripts of Google and Facebook (and some other external scripts like Intercom) in TypeScript by loading them through a script tag. With most of them, I have issues, because I don't have types from them that I can actually import and use.
For example with Facebook, I've installed the package @types/facebook-js-sdk
from DefinitelyTyped
, which allows me to see the type of window.FB
, because it's declared in the namespace from the types package. However, I can't seem to use or import any type to type window.FB
when I'm passing it to some other code for example, see code below.
// window.FB is typed here
const fb = new Facebook(window.FB)
class Facebook {
// How can I type fb here?
constructor(fb) {
this.fb = fb
}
Is there any way I can use the namespace to get types? Do I need to write the types myself in this case? Open to suggestions!
答案1
得分: 1
你可以通过使用 typeof
来获取你的已定义窗口变量的类型。
例如:
class Facebook {
fb: typeof window.FB
constructor(fb: typeof window.FB) {
if (typeof fb === 'undefined') {
throw new Error('The Facebook API is not initialized!')
}
this.fb = fb
}
}
英文:
You can get the type for your typed window variable by doing typeof
.
So for example
class Facebook {
fb: typeof window.FB
constructor(fb: typeof window.FB) {
if (typeof fb === 'undefined') {
throw new Error('The Facebook API is not initialized!')
}
this.fb = fb
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论