2017-04-25 106 views
0

我想在打字稿項目中使用小型JavaScript庫。 (對於full example see here)。使用Typescript默認導出

JavaScript庫定義如下:

"use strict"; 

exports.__esModule = true; 
exports["default"] = functionOfInterest; 
function functionOfInterest(val) { } 
module.exports = exports["default"]; 

這已經使用.d.ts文件類型爲:

export default function functionOfInterest(val: number): void; 

在打字稿文件我用:

import functionOfInterest from "the-package"; 

functionOfInterest(1); // invoke it. 

這編譯爲:

"use strict"; 
Object.defineProperty(exports, "__esModule", { value: true }); 
var functionOfInterest_1 = require("the-package"); 
functionOfInterest_1.default.apply(void 0, 1); 

與此錯誤:

TypeError: Cannot read property 'apply' of undefined 

tsconfig.json文件是:

{ 
    "compilerOptions": { 
    "outDir": "js", 
    "module": "commonjs", 
    "declaration": true, 
    "target": "es5", 
    "lib": ["es6", "dom"], 
    "sourceMap": true, 
    "jsx": "react", 
    "moduleResolution": "node", 
    "rootDir": "ts", 
    "forceConsistentCasingInFileNames": true, 
    "noImplicitReturns": true, 
    "noImplicitThis": true, 
    "noImplicitAny": true, 
    "strictNullChecks": true, 
    "suppressImplicitAnyIndexErrors": true, 
    "noUnusedLocals": true 
    }, 
    "exclude": [ 
    "node_modules", 
    "build" 
    ] 
} 

我敢肯定有隻是一個簡單的配置錯誤的地方,但我不能在此刻看着辦吧。

打字稿2.2.2

回答

0

你必須使用:

import functionOfInterest = require("the-package"); 

(functionOfInterest as any)(1); 

** 或者 **

您可以更改定義文件:

declare function functionOfInterest(val: number): void; 
export = functionOfInterest; 

然後消耗沒有投到any

import functionOfInterest = require("the-package"); 

functionOfInterest(1); 
0

試試這個:

import * as _ thePackage from "the-package"; 

thePackage.functionOfInterest(1); 
+0

隨着打字稿2.2.2,這個錯誤有:'文字預期[TS]字符串。 [ts]'來自'預期。 any' – AJP