在 Typescript 中显式设置 Intercom 窗口类型会引发错误

met*_*lah 6 typescript

根据此处的讨论,我必须扩展窗口对象才能强类型 Intercom 的窗口功能。

最初的代码是这样的:

  setCurrentRoute() {
    if (
      this.currentRoute.getValue().indexOf('website') > -1 ||
      this.currentRoute.getValue().indexOf('builder') > -1
    ) {
      (window as any).Intercom('update', {
        hide_default_launcher: true,
      });
    } else {
      (window as any).Intercom('update', {
        hide_default_launcher: false,
      });
    }
    localStorage.setItem('currentRoute', this.currentRoute.getValue());
  }
Run Code Online (Sandbox Code Playgroud)

但当我尝试利用更多 Typescript 的类型安全功能时,它现在看起来像这样:

  declare global {
    interface Window {
      Intercom(update: string, params: { hide_default_launcher: boolean }): void;
    }
  }

  setCurrentRoute(): void {
    if (this.currentRoute.getValue().indexOf('website') > -1 || this.currentRoute.getValue().indexOf('builder') > -1) {
      this.window.Intercom('update', {
        'hide_default_launcher': true
      });
    } else {
      this.window.Intercom('update', {
        'hide_default_launcher': false
      });
    }
    localStorage.setItem('currentRoute', this.currentRoute.getValue());
  }
Run Code Online (Sandbox Code Playgroud)

但是,我收到以下错误消息:

ERROR TypeError: Cannot read property 'Intercom' of undefined
    at RouterService.push../src/app/shared/services/router.service.ts.RouterService.setCurrentRoute
Run Code Online (Sandbox Code Playgroud)

我如何解决它?

Ben*_*ing 14

带打字稿的对讲机

以下是我如何让打字稿和对讲机工作:

  1. 包括依赖项yarn add -D @types/intercom-web
  2. 编辑你的tsconfig.json
{
  "compileOnSave": false,
  "compilerOptions": {
    ....,
    "types": [...., "@types/intercom-web"]
  }
}
Run Code Online (Sandbox Code Playgroud)
  1. 现在,引用时类型将显示在代码中,window.Intercom并且命名空间Intercom_将全局可用,例如:Intercom_.IntercomSettings


met*_*lah 0

我设法通过执行以下操作来修复它:

export interface RouterWindow extends Window {
  Intercom(update: string, params: { hide_default_launcher: boolean }): void;
}

  setCurrentRoute(): void {
    if (this.currentRoute.getValue().indexOf('website') > -1 || this.currentRoute.getValue().indexOf('builder') > -1) {
      (<RouterWindow>window).Intercom('update', {
        'hide_default_launcher': true
      });
    } else {
      (<RouterWindow>window).Intercom('update', {
        'hide_default_launcher': false
      });
    }
    localStorage.setItem('currentRoute', this.currentRoute.getValue());
  }
Run Code Online (Sandbox Code Playgroud)