TypeScript First Program

In this section, we are going to learn how we can write a program in TypeScript, how to compile it, and how to run it. Also, we will see how to compiles the program and shows the error, if any.

Let us write a program in the text editor, save it, compile it, run it, and display the output to the console. To do this, we need to perform the following steps.

Step-1 Open the Text Editor and write/copy the following code.

snippet
function greeter(person) {
    return "Hello, " + person;
}
let user = 'rookienerd';
console.log(greeter(user));

Step-2 Save the above file as ".ts" extension.

Step-3 Compile the TypeScript code. To compile the source code, open the command prompt, and then goes to the file directory location where we saved the above file. For example, if we save the file on the desktop, go to the terminal window and type: - cd Desktop/folder_name. Now, type the following command tsc filename.ts for compilation and press Enter.

TypeScript First Program

It will generate JavaScript file with ".js" extension at the same location where the TypeScript source file exists. The below ".js" file is the output of TypeScript (.ts) file.

TypeScript First Program
Note
NOTE: If we directly run ".ts" file on the web browser, it will throw an error message. But after the compilation of ".ts" file, we will get a ".js" file, which can be executed on any browser.

Step-4 Now, to run the above JavaScript file, type the following command in the terminal window: node filename.js and press Enter. It gives us the final output as:

TypeScript First Program

Compile-Time error

TypeScript always gives an error at compilation time. For this, we need to write the program in TypeScript, compile it, and see the error, if found.

Step 1 Open the Text Editor and write/copy the following code.

snippet
function addNumbers(a, b) {
    return a + b;
}
var sum = addNumbers("rookienerd", 25);
console.log('Sum of the numbers is: ' + sum);

Step-2 Save the above file as ".ts" extension.

Step-3 Compile the TypeScript code. To compile the source code, open the command prompt, and then goes to the file directory location where we saved the above file. For example, if we save the file on the desktop, go to the terminal window and type: - cd Desktop/folder_name. Now, type the following command tsc filename.ts for compilation and press Enter.

This TypeScript source file will generate an error which can be shown in the following image.

TypeScript First Program
Note
NOTE: This program gives an error because we were taking the variable "a" and "b" as of number type. But, we were passing the variable "a" as the string and variable "b" as the number.
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +