Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Using TypeScript for pure JavaScript

    Basarat Ali SyedBasarat Ali Syed

    TypeScript can actually be used just as a JavaScript -> JavaScript Transpiler e.g. ES6 -> ES5. This allows you to easily maintain your old JavaScript code base along with potentially uplifting to a TypeSafe version using a single compiler.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    Here I have a JavaScript file that exports a log function that simply logs the message, "Hello, World!" to the console. We can easily go ahead and create another JavaScript file that requires this utils file and uses its log function.

    Note this is all just built in a node-style JavaScript. We can actually use TypeScript as a transpiler for build JavaScript projects simply by adding a TS tsconfig.json. We will use this file to configure the types of compiler options. We set our transpiler output target to ES5.

    We set allow JS to true, which tells the TypeScript compiler to support raw .js files, and an out DAR to provide the output location for transpiled JavaScript. Finally, we include all the files in the source directory.

    Now, if I go ahead and set this tsconfig as my active project, you can see that the TypeScript compiler picks up these JS files in our source directory, as indicated by the green highlighting. I can even go ahead and transpose these JavaScript files to our output lib directory.

    One advantage of using TypeScript as a transpiler in this way is that you get to use the latest JavaScript features. For example, I could go ahead and replace the function keyword with an arrow function, and you can see that the output JavaScript remains unchanged as I set my compile output target to ES5.

    I can even use other ES features, for example, ES6 exports. Similarly, I can use ES6 imports to use the log function from the utils module. Of course, this shows another great reason to use TypeScript for JS files, which is this excellent autocomplete.

    Additionally, for raw JavaScript files, TypeScript also gives you some tactic-checking to protect against simple errors. Finally, you have the ability to mix and match JavaScript and TypeScript in the same project.

    If I go ahead and change the file extension from JS to TS, it opens up advanced TypeScript analysis. Mixing JS and TS files this way allows you to incrementally upgrade your code base towards greater type safety provided by TS files.