Using TypeScript for pure JavaScript

Share this video with your friends

Send Tweet
Published 6 years ago
Updated 4 years ago

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.

[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.

peterschussheim
peterschussheim
~ 6 years ago

What editor are you using?

also, why use this method instead of babel?

Basarat Ali Syed
Basarat Ali Syedinstructor
~ 6 years ago

What editor are you using?

http://alm.tools/ Created specifically to give a reliable deterministic TypeScript experience so I don't have to fight the IDE when teaching (or even doing real world projects).

Why use this method instead of babel?

Autocomplete is a big one. Plus a smooth migration to TypeScript proper if you ever wanted 🌹