打字稿:使用“ .d.ts”文件向“窗口”添加功能

Ste*_*fan 4 typescript

我有一个旧版* .js应用程序,想将其部分移植到打字稿上。

到目前为止,我已经为大多数使用的软件包找到了@types定义,但是在window对象中添加了一个全局函数。

我能够通过在* .ts文件开头添加addind来解决编译错误:

declare global {
    interface Window {
        openConformationModal?: any;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,我不想在我所有的* .ts中都包含它,所以我想将其添加到* .d.ts文件中,以便在所有软件包中都可以识别它。

问题是,如果我将同一文件添加到例如window.d.ts文件,则无法识别该文件。我知道找到了文件夹中的类型,因为我添加了

 {
  ...,
  "compilerOptions": {
    ....
    "typeRoots": [
      "FFOLDERPATH_TO_D_TS_FILE"
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

并且找到另一个* .d.ts。

PS:解决方案基于您如何在TypeScript中的“ window”上显式设置新属性?

Ste*_*fan 5

我在这个问题的下方找到了它:https : //stackoverflow.com/a/40698148

interface Window {
  MyNamespace: any;
}
Run Code Online (Sandbox Code Playgroud)

完整答案:

如果您使用的是TypeScript定义管理器,请执行以下操作

npm install typings --global
Run Code Online (Sandbox Code Playgroud)

创建typings/custom/window.d.ts

interface Window {
  MyNamespace: any;
}

declare var window: Window;
Run Code Online (Sandbox Code Playgroud)

安装您的自定义键入:

typings install file:typings/custom/window.d.ts --save --global
Run Code Online (Sandbox Code Playgroud)

完成,使用它‌!打字稿不会再抱怨了:

window.MyNamespace = window.MyNamespace || {};
Run Code Online (Sandbox Code Playgroud)