如何在TypeScript / TSX中使用外部命名空间的类型

huangapple go评论53阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年2月7日 05:13:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/75366641.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定