Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson

Already subscribed? Sign In


    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


    00:00 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.

    00:16 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.

    00:35 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.

    00:51 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.

    01:09 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.

    01:25 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.

    01:44 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.

    01:57 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.