Typescript给window对象添加全局变量

28,085 阅读1分钟

目前使用typescript的时候,遇到一个问题,有2种情形

  1. 使用第三方库时(ga),ga是全局方法,在使用时会提示" 类型“Window”上不存在属性“ga” "。
  2. 由一些旧文件,之前写的时全局变量,挂载在window下,那么在其他地方式使用时也存在问题,提示也是类似 " 类型“Window”上不存在属性“ga” "。

搜索问题,给到的方法大都时这样处理

declare global {
    interface Window {
        test: string;
    }
}

而实际上这个方法在typescript 3.4之后就无效了,提示

Augmentations for the global scope can only be directly nested in external modules or ambient module declarations.

最新的解决方法是,建一个声明文件(比如index.d.ts)

    interface Window {
        test: string;
    }

解决问题