JavaScript to TypeScript Conversion

In this blog we are going to know how to convert javascript files to typescript files. Even though while compiling a typescript file it will produce javascript files with the same name , we have to ensure that the original javascript file which acts as input , is present in a directory so that typescript should not override them. So in addition to that we will keep all output files in an output directory called dist.

Steps to convert JS files to TS Files: 

  1. Add tsconfig.json file
  2. Integrate webpack with build tool
  3. Change all .js files to .ts files
  4. Check for errors

Add tsconfig.json file

Once we add tsconfig.json to our project, it starts managing project compilation as well as which file to include and exclude

We include all the files from the src, using the “include” option.

Inside compilerOptions , “outDir” will redirect all the output files to a folder called “dist”

“allowJs” will allow all js files, so it is set to true

“target” specifies all js constructs should translate to ECMAScript 6

Integrate webpack with build tool

npm install awesome-typescript-loader source-map-loader

We have to run the above command in our terminal.

Awesome-typescript-loader is a typescript loader

Source-map-loader is used for debugging our source code


We can add/edit the above file to include these two loaders

Change all .js files to .ts files

Rename our first .js file to .ts file. Once you change the file name, it will start giving compilation errors.

Check for errors: 

Typescript has strict type checking , so we will notice lots of errors in our code.

For example: 

The above code will compilation error in typescript like 

Property ‘id’ does not exist on type ‘{}’

Property ‘name’ does not exist on type ‘{}’

So to resolve this, we have to move all the properties inside object like below

Or we can create interface like below

Third Party Javascript Libraries: 

Most of our Javascript projects use the jquery library . Typescript needs to know the types of all the objects in the jquery library to compile files. For that we need to install “types” for the jquery library 

npm install @types/jquery

Once you made all the above said changes, run our build tool . Now we have our typescript project compiled into plain javascript that we can run in our browser. 

Leave A Comment

Your email address will not be published. Required fields are marked *