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!
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
}
}