How To Convert Javascript to TypeScript

Previously I use Babel Javascript to convert my javascript to ECMA2015. I like to program in object oriented because I learned my first programming language in C/C++ and Java.

Doing procedural language like C was much easier vs object oriented Java. But in the long run, I noticed that coding in object oriented is much easier to maintain.

Steps to Convert Javascript to TypeScript

Install TypeScript

-g to make it global so all your JavaScript programs can be migrated to TypeScript.

Create tsconfig.build.json, tsconfig.json and tslint.json

At your root project folder run the below command.

I edited my tsconfig.json as follows:

I added manually tsconfig.build.json and tslint.json

tslint.json

Change Your Existing Files Extension from .js to .ts

typescript change all js to ts extension
typescript change all js to ts extension
typescript change all js to ts extension
typescript change all js to ts extension

Amend Coding T0 Follows TypeScript

Below are few examples TypeScript coding standard that you must follow.

If you Find below error, add return true at main async function.

typescript error promise contructor
typescript error promise contructor

Besides, you can use TypeScript linter @ tslint (that was set up early) to fix any coding that doesn’t follow TypeScript standard. TypeScript standard is more strict vs JavaScript.

Example of tslint verbose message:

typescript tslint
typescript tslint

Run Unit Test

I use mocha to do unit test.

At package.json, add new script command

Example if you want to run one individual unit test.

If you found Error Cannot find module ‘ts-node/register’

Solution: save ts-node locally as develepment dependency.

Run TypeScript Application

At the terminal or console, type

Conclusion

Even though it takes time to convert from babel javascript into typescript but in the long run it is easier to understand the code and easier to maintain the code.

Besides, you just need to install ts-node and its linter is very good in displaying possible errors.

Benefits of using TypeScript

  • Easy debugging – Typescript shows directly line that throws an error
  • Strong type – any mismatch of variable will be highlighted by ts-lint
  • Less transpilation time – no need to compile like babel. If you have lots of .js files, it takes time to transpile it
  • Support better object oriented – it supports abstract, protected, private methods and variables.