Calling properly TypeScript code from JavaScript

后端 未结 5 1585
生来不讨喜
生来不讨喜 2020-12-03 11:36

On our big enterprise project we faced a situation that seems not to be very well described in the articles and the posts available in the Internet.

We need to integ

5条回答
  •  甜味超标
    2020-12-03 12:32

    The justification that TypeScript is essentially compiled into JavaScript seems to be obscure because there are no trustful sources on information on the topic on how to properly consume that compiled JavaScript from handwritten JavaScript and what are the hidden caveats

    Consuming TypeScript from JavaScript is the same as consuming TypeScript from TypeScript, or JavaScript from JavaScript for that matter. For example, let's say you have a function in TypeScript:

    function f(n: number) { return 'the number is ' + n; }
    

    To call this function from TypeScript, you would write

    var x = f(42);
    

    To call this function from JavaScript, you would write

    var x = f(42);
    

    Let's say you have a class in TypeScript:

    class MyClass { /* ... */ }
    

    To use this class from TypeScript, you would write

    var c = new MyClass();
    

    To use this class from JavaScript, you would write

    var c = new MyClass();
    

    In other words, it's exactly the same. No guidance has been given because none is needed.

提交回复
热议问题