In this section, we will explore the process of writing a program in TypeScript, compiling it, and executing it. Additionally, we will examine how to compile the program and display any errors that may arise.
We will create a program using the text editor, save the file, compile it, execute it, and show the output in the console. To accomplish this, we must follow these steps.
Step 1: Launch the Text Editor and either type or paste the code provided below.
function greeter(person) {
return "Hello, " + person;
}
let user = 'TypeScript Tutorial';
console.log(greeter(user));
Step-2 Save the above file as " .ts " extension.
Step-3 Compile the TypeScript code. To compile the source code, launch the command prompt and navigate to the directory where the file was saved. For instance, if the file is located on the desktop, access the terminal and enter: - cd Desktop/folder_name. Next, input the command tsc filename.ts to initiate the compilation and hit Enter.
A JavaScript file with a ".js" extension will be created in the same directory as the TypeScript source file. The following ".js" file represents the output generated from the TypeScript (.ts) file.
Running TypeScript Files in the Browser
Step-4 To execute the previously mentioned JavaScript file, enter the following command in the terminal window: node filename.js and hit Enter. This will provide us with the final output as:
Compilation Error
TypeScript consistently produces an error during the compilation phase. To address this, we must develop the program using TypeScript, compile it, and check for any errors that may arise.
Step 1 Launch the Text Editor and either compose or paste the subsequent code.
function addNumbers(a, b) {
return a + b;
}
var sum = addNumbers("TypeScript Tutorial", 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 initiate the compilation of the source code, access the command prompt and navigate to the directory where the file was stored. For instance, if the file is located on the desktop, enter the terminal and input: - cd Desktop/folder_name. Next, execute the command tsc filename.ts to compile the code and hit Enter.
This TypeScript source file is expected to produce an error, as illustrated in the image below.