Tutorialsteacher

Follow Us

First TypeScript Program: Compile and Run

Here, you will learn to write a simple program in TypeScript, compile it and use it in the web page.

Create a new file in your code editor and name it add.ts and write the following code in it.

File: add.ts
function addNumbers(a: number, b: number) { 
    return a + b; 
} 

var sum: number = addNumbers(10, 15) 

console.log('Sum of the two numbers is: ' +sum);

The above TypeScript code defines the addNumbers() function, call it, and log the result in the browser's console.

Now, open the command prompt on Windows (or a terminal on your platform), navigate to the path where you saved add.ts, and compile the program using the following command:

tsc add.ts

The above command will compile the TypeScript file add.ts and create the Javascript file named add.js at the same location. The add.js file contains the following code.

File: add.js
function addNumbers(a, b) {
    return a + b;
}

var sum = addNumbers(10, 15);

console.log('Sum of the two numbers is: ' + sum);

As you can see, the TypeScript compiler compiled add.ts TypeScript file to Javascript file ad.js. You can now include the add.js file in a web page using a script tag and see the result in the browser's developer console.

Now, let's see how TypeScript compiles the program if we pass a string parameter to the addNumbers() function instead of a number.

Replace var sum:number = addNumbers(10, 15) in add.ts with var sum:number = addNumbers(10,'abc')and recompile the add.ts file in the terminal. You will get the following compilation error!

C:\> tsc add.ts
add2.ts(5,32): error TS2345: Argument of type 'abc' is not assignable to parameter of type 'number'.

So, TypeScript does not compile the code if you pass a string to a function that is expecting a number! Most IDE will display TypeScript errors instantly without compiling the code.

Thus, static type-checking with type annotations and several other TypeScript features like interface, class, and module help programmers write cleaner and more scalable code that can be shared across teams.