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.
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.
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.
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 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.
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.