We all know that TypeScript is a language that compile itself to JavaScript. During compile-time TypeScript can emit errors to a terminal, and does not allow compiling of a code at all.

Even if you are writing pure JavaScript code, we can still use TypeScript compiler to detect possible errors during compile-time, instead of testing and encountering them on run-time. Which can be very expensive ( the billion dollar mistake ).

Most used tools for detecting problems during compilation in JavaScript are linters. Linters can be configured in a very strict way, which can enhance quality of a code significantly.

Using TypeScript compiler to do that work for us has additional advantages like:

Having TypeScript ( .ts ) files in a project and use some really cool features from TypeScript language. ( slowly migrating project to a TypeScript )

Compile to a different JavaScript versions.

Configuring project to use TypeScript compiler

Configuring your JavaScript project should be pretty easy.

We have to add TypeScript as a dependency to a project:

npm install typescript --save-dev

After that, we have to create tsconfig.json in a root of a project. I have chosen the following configuration for this demo, but you can tune or change whatever you want.

List of all possible values you can find here: TypeScript compiler options.

tsconfig.json

Most important flags here are:

allowJs and checkJs, which as a name implies allowing JavaScript in a project and compiling it.

noImplicitAny must be turned off, because we are not able to define types in JavaScript.

dist is a folder where we will save compiled code.

src folder is a root of our source code.

We will register in our package.json additional script for compilation:

"scripts": {

"compile": "tsc"

},

Demo time

Let’s create simple file in src folder called app.js and put some code there:

Above code, Node.js interpreter will successfully interpret it. Result will be:

Car { name: 'BMW' }

If we try to compile it with defined npm run compile script, compiler will emit the error: