【问题标题】:How to 'import' a third party Javascript file into IntelliJ so that I can refer to it in a Typescript file如何将第三方 Javascript 文件“导入”到 IntelliJ 中,以便我可以在 Typescript 文件中引用它
【发布时间】:2013-11-23 11:59:08
【问题描述】:

我正在尝试在 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

【问题讨论】:

    标签: node.js intellij-idea typescript


    【解决方案1】:

    您可以将 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;
            }
        }
    }
    

    【讨论】:

    • 您的回答和this answer about importing 都有帮助 - 谢谢。我讨厌在评论中提出问题,但是有什么工具可以从 Javascript 文件神奇地创建 d.ts 文件?
    • 没什么神奇的——尽管你总是可以尝试将 JavaScript 粘贴到 .ts 文件中,看看 TypeScript 编译器是如何处理它的。有时,缺少的类型注释是不可猜测的。
    猜你喜欢
    • 2017-04-30
    • 1970-01-01
    • 1970-01-01
    • 2012-10-03
    • 2020-03-22
    • 2013-02-27
    • 2013-10-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多