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

npm install -g 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.

tsc --init

I edited my tsconfig.json as follows:

{
  "compilerOptions": {
    "target": "es2017",
    "module": "commonjs",
    "lib": [ "dom", "dom.iterable", "esnext"],
    "rootDir": ".",
    "moduleResolution": "node",
    "resolveJsonModule": true,

    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "types": ["node", "mocha", "chai"],
    "typeRoots": ["node_modules/@types", "src/types"],
    "jsx": "react"    
  },
  "exclude": ["node_modules", "dist", "src/admin"],

  "include": [ "src/**/*.ts", "src/**/*.json"]
}

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

{
  "extends": "./tsconfig.json",
  "exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
}

tslint.json

{
  "defaultSeverity": "error",
  "extends": [
    "tslint:recommended"
  ],
  "jsRules": {
    "no-unused-expression": true
  },
  "rules": {
    "quotemark": [
      true,
      "double"
    ],
    "member-access": [
      false
    ],
    "ordered-imports": [
      false
    ],
    "max-line-length": [
      true,
      150
    ],
    "member-ordering": [
      false
    ],
    "interface-name": [
      false
    ],
    "arrow-parens": false,
    "object-literal-sort-keys": false
  },
  "rulesDirectory": []
}

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.

#1 - require to import
const Humanoid = require("./humanoid/index.js");

//change require to import & remove file extension
import {Humanoid} from "./humanoid/index";

#2 - add export in front of class and remove module.exports
export class Humanoid extends HumanoidReqHandler

//remove all line that have module.exports
module.exports = Humanoid; //delete this line

#3 - declare all global variables inside a class as class variables
this.taskName = "something";

//then can call this.taskName inside your class after declare the variable name
protected taskName: string;

//#4 - declare abstract method by adding keyword abstract
//example of javascript - abstract method
if(this._execute === undefined){
	throw new Error("Abstract method _execute()");
}

//put abstract in front of class keyword
abstract class Task{
    constructor(){}
    abstract _execute() : any;
}

//#5 - use import * as something from 'somewhere'
//if error class name .default is not a function decla
//example
import m from 'moment';
TypeError: moment_1.default is not a function

//change to
import * as m from 'moment';

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

typescript error promise contructor
typescript error promise contructor
(async function() {
  console.log('start program');
  console.log('end program');
  return true; //add return true to solve error
}());

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.

npm install --save-dev @types/mocha

At package.json, add new script command

"scripts":{
... //other commands
"test-filename": "mocha -r ts-node/register"
},

Example if you want to run one individual unit test.

npm run test-filename ./-- -g "./src/lib/utils/date-timestamp.test.ts"

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

Solution: save ts-node locally as develepment dependency.

npm install ts-node --save-dev

Run TypeScript Application

At the terminal or console, type

ts-node path-to-your-main-file

//example
ts-node ./src/main.ts

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.