ES5 匿名函数的打字稿导入
Typescript import of an ES5 anonymous function
我正在使用 ES6 导入语法并导入第 3 方 ES5 模块,该模块导出一个未命名函数的导出:
module.exports = function (phrase, inject, callback) { ... }
因为没有默认导出,而是一个匿名函数输出,所以我必须像这样导入和使用:
import * as sentiment from 'sentiment';
const analysis = sentiment(content);
这给出了 Typescript 错误:
error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'typeof "sentiment"' has no compatible call signatures.
我想我是因为我没有正确输入 ES5 导入文件(没有 public 类型文件)。当我虽然函数是 default export 时,我有以下定义:
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;
};
虽然这似乎是一个有效的导出定义,但它与匿名调用定义不匹配并抛出以下错误:
error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'typeof "sentiment"' has no compatible call signatures.
在这种情况下,您将无法以这种方式导入。
正如 Modules: export = and import = require() 中所述:
When importing a module using export =, TypeScript-specific import let
= require("module") must be used to import the module.
所以你必须这样做:
import sentiment = require("sentiment");
const analysis = sentiment(content);
定义文件可能如下所示:
declare function fn(contents: string, overRide?: IDictionary<number>): IResults;
export = fn;
我正在使用 ES6 导入语法并导入第 3 方 ES5 模块,该模块导出一个未命名函数的导出:
module.exports = function (phrase, inject, callback) { ... }
因为没有默认导出,而是一个匿名函数输出,所以我必须像这样导入和使用:
import * as sentiment from 'sentiment';
const analysis = sentiment(content);
这给出了 Typescript 错误:
error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'typeof "sentiment"' has no compatible call signatures.
我想我是因为我没有正确输入 ES5 导入文件(没有 public 类型文件)。当我虽然函数是 default export 时,我有以下定义:
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;
};
虽然这似乎是一个有效的导出定义,但它与匿名调用定义不匹配并抛出以下错误:
error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'typeof "sentiment"' has no compatible call signatures.
在这种情况下,您将无法以这种方式导入。
正如 Modules: export = and import = require() 中所述:
When importing a module using export =, TypeScript-specific import let = require("module") must be used to import the module.
所以你必须这样做:
import sentiment = require("sentiment");
const analysis = sentiment(content);
定义文件可能如下所示:
declare function fn(contents: string, overRide?: IDictionary<number>): IResults;
export = fn;