Angular2 和 Typescript:错误 TS2339:属性 'selectpicker' 在类型 'ElementFinder' 上不存在

Angular2 & Typescript: Error TS2339: Property 'selectpicker' does not exist on type 'ElementFinder'

不幸的是,我们必须在当前项目中使用需要 jQuery 的旧库。它们的激活发生在生命周期挂钩部分 "ngAfterViewChecked"。由于 TypeScript 无法在正确的时间解析它,它输出错误:

Error TS2339: Property 'selectpicker' does not exist on type 'ElementFinder'.

这是相关的代码块:

 ngAfterViewChecked () {
    if (this.agency) {
      //noinspection TypeScriptUnresolvedFunction
      $('.selectpicker').selectpicker();
    }
  }

我在激活选择器之前添加了行 //noinspection TypeScriptUnresolvedFunction,但没有帮助。

我们有一个预配置的构建系统,由于这样的错误,它 "bounces" 我们。我怎样才能摆脱这个问题?

您必须扩展 jQuery 的类型定义。这意味着将 jQuery 命名空间与定义 .selectpicker() 方法的自定义 .d.ts 合并。请参阅文档以获取帮助:

https://www.typescriptlang.org/docs/handbook/writing-declaration-files.html

根据您的 jQuery 定义文件,这可能有效:

interface JQuery {
  selectpicker: () => void;
}