【问题标题】:Typescript import of an ES5 anonymous functionES5匿名函数的打字稿导入
【发布时间】:2017-05-16 03:02:56
【问题描述】:

我正在使用 ES6 导入语法并导入第 3 方 ES5 模块,该模块导出一个未命名函数的单个导出:

module.exports = function (phrase, inject, callback) { ... }

因为没有默认导出,而是一个匿名函数输出,所以我必须像这样导入和使用:

import * as sentiment from 'sentiment';
const analysis = sentiment(content);

这给出了 Typescript 错误:

错误 TS2349:无法调用其类型缺少调用签名的表达式。类型 'typeof "sentiment"' 没有兼容的调用签名。

我想我得到了这个,因为我没有正确输入 ES5 导入(没有公共类型文件)。当我虽然函数是 默认导出时,我有以下定义:

interface IResults {
  Score: number;
  Comparitive: number;
}

declare var fn: (contents: string, overRide?: IDictionary<number>) => IResults;

declare module "sentiment" {
  export default fn;
};

这一切都说得通,但由于导入 不是默认导出,我不知道如何定义这个模块和函数。我确实尝试了以下方法:

declare module "sentiment" {
  export function (contents: string, overRide?: IDictionary<number>): IResults;
};

虽然这似乎是一个有效的导出定义,但它与匿名调用定义不匹配并引发以下错误:

错误 TS2349:无法调用其类型缺少调用签名的表达式。类型 'typeof "sentiment"' 没有兼容的调用签名。

【问题讨论】:

    标签: typescript typescript-typings


    【解决方案1】:

    在这种情况下,您将无法以这种方式导入。
    正如Modules: export = and import = require() 中所述:

    当使用 export = 导入模块时,TypeScript 特定的 import let = require("module") 必须用于导入模块。

    所以你必须这样做:

    import sentiment = require("sentiment");
    const analysis = sentiment(content);
    

    定义文件应该如下所示:

    declare function fn(contents: string, overRide?: IDictionary<number>): IResults;
    export = fn;
    

    【讨论】:

      猜你喜欢
      • 2023-01-17
      • 2022-11-26
      • 1970-01-01
      • 1970-01-01
      • 2017-09-09
      • 1970-01-01
      • 2019-08-10
      • 2021-07-12
      • 1970-01-01
      相关资源
      最近更新 更多