【问题标题】:How to attach the type to a library globally available on Typescript如何将类型附加到 Typescript 上全局可用的库
【发布时间】:2020-05-20 11:26:38
【问题描述】:

我正在使用老式方式加载一个 JS 库(DOM 中的 loadScript、<script>,无论如何...),我有可用的类型,但我不明白如何告诉 Typescript @ 987654322@ 是我库的构造函数,与我已有的类型匹配。

假设这个导入将同时导入依赖项和类型

import { MyLibrary } from "myLibrary";


[..]


new MyLibrary("#div", {}); 

这对我的堆栈来说太新了。我只想使用 Webpack 导入类型并将其附加到一些 window['myLibrary'] 变量,但仍然是 typescript 类型的好处。

【问题讨论】:

    标签: typescript webpack typescript-typings


    【解决方案1】:

    这是将类型附加到库实例的方法

    // Import the typings directly
    import { MyLibrary } from "../../../../../defs/myLib-4.5";
    
    [...]
    
    
    // the magic line that attach the type to the window attribute
    const GlobalLibraryConstructor = (window as any)['myLibrary'] as typeof MyLibrary;
    this.table = new GlobalLibraryConstructor("#div", {}); 
    

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 2020-09-30
      • 1970-01-01
      • 2020-09-10
      • 1970-01-01
      • 2019-09-29
      • 1970-01-01
      • 2018-10-12
      • 1970-01-01
      • 2020-05-24
      相关资源
      最近更新 更多