1

我正在尝试在 IntelliJ 中编写 Typescript,但不知道如何告诉 IntelliJ“导入”一些第三方 Javascript 文件。IntelliJ(或者是 Node.JS?)给出了以下抱怨:

C:/Temp/Typescript Example Project/ts/FinancialService.ts(2,17): error TS2095: Could not find symbol 'com'.
C:/Temp/Typescript Example Project/ts/FinancialService.ts(4,31): error TS2095: Could not find symbol 'com'.

我想“导入” Thirdparty.Calculator.js

var com = com || {};
com.thirdparty = com.thirdparty || {};
com.thirdparty.Calculator = function() {
    this.add = function(a, b) {
        return a + b;
    };
    this.square = function(n) {
        return n*n;
    };
};

这就是FinancialService.ts的样子:

class FinancialService {
    calculator: com.thirdparty.Calculator;
    constructor() {
        this.calculator = new com.thirdparty.Calculator();
    }
    calculateStuff(a: number) {
            return this.calculator.square(a);
    }
}

IntelliJ 似乎将 Typescript 转换为以下工作,并将正确的值记录到控制台:

<html>
    <head>
        <script src="js/Thirdparty.Calculator.js"></script>
        <script src="ts/FinancialService.js"></script>

        <script>
            var cal = new com.thirdparty.Calculator();
            console.log("Calculator.square() is " + cal.square(9));

            var fs = new FinancialService();
            console.log("FinancialService.calculateStuff() is " + fs.calculateStuff(4));
        </script>
    </head>
    <body>
    </body>
</html>

如何配置我的项目以便 IntelliJ 知道Thirdparty.Calculator.js

4

1 回答 1

2

您可以添加Thirdparty.Calculator.d.ts到项目中以进行 TypeScript 编译:

declare module com.thirdparty {
    export class Calculator {
        add(a: number, b: number) : number;
        square(n: number) : number;
    }
}

这显然需要与第三方库一起增长。

只需很少的额外努力,您就可以将其转换为 TypeScript...

module com.thirdparty {
    export class Calculator {
        add = function(a: number, b: number) {
            return a + b;
        };
        square(n: number) : number {
            return n*n;
        }
    }
}
于 2013-11-11T16:41:43.470 回答