[TypeScript] Tutorial for Compiling TypeScript & Compiler Options

·

2 min read

[TypeScript]  Tutorial for Compiling TypeScript & Compiler Options

Introduction

This article will be a tutorial/guide for those who want to know how to compile your TypeScript file into a JavaScript file.

Moreover, I will be introducing what is a compiler option, and what options you can give to a compiler.


Downloading Node.js

In order to compile the TS file, please make sure that you have downloaded node.js with a version later than 10. If you want to check if node.js is already installed, open a terminal or cmd to type a command.

node -v

If you have node.js you will get the version name.

If not, please download the LTS version here: Node.js


Compiling

In TypeScript, you need to "compile" your TypeScript file into a JavaScript file to run your program.

That's what compiling means. It's just like converting your .doc file into .pdf file.

Let's say we have this TypeScript file (index.ts):

function sum(a: number, b: number): number {
    return a + b;
}

console.log(sum(10, 20));

Right-click on the folder that has the TypeScript file you want to compile.

Open the terminal

Install TypeScript Globally

Compile TypeScript

Compile TS file by using a command tsc (stands for TypeScript Compile) followed by the file name.

Now you have index.js, which is a JavaScript file (index.js):

function sum(a, b) {
    return a + b;
}
console.log(sum(10, 20));

Compared to a TypeScript file (index.ts):

function sum(a: number, b: number): number {
    return a + b;
}

console.log(sum(10, 20));

Compiler Options

When you compile your TypeSript file, you can give options to it.

For example:

{
    "complierOptions": {
        "allowJs": true, 
        "checkJs": true, 
        "noImplicitAny": true     
    }
}
// https://www.typescriptlang.org/tsconfig

Those are only a few of the compiler options.

If you want to find out more about it, TypeScript's website has a list of them.

TypeScript website: TypeScript: TSConfig Reference

Did you find this article valuable?

Support Jay's Dev Blog by becoming a sponsor. Any amount is appreciated!