TypeScript Beginner Tutorial 3 | 1st Program | Hello World

3 min read 11 months ago
Published on Sep 11, 2024 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

In this tutorial, you will learn how to create your first TypeScript program, "Hello World," using Visual Studio Code (VS Code). This guide will walk you through the steps to set up your environment, write basic TypeScript code, compile it to JavaScript, and run it. Understanding these foundational concepts is essential for anyone looking to start programming in TypeScript.

Step 1: Set Up Your Project Folder

  • Create a new folder where you want to store your TypeScript project.
  • Open this folder in Visual Studio Code by selecting File > Open Folder.

Step 2: Create a TypeScript File

  • Inside the newly created folder, create a new file named basics.ts.
  • You can do this by right-clicking in the Explorer panel and selecting New File, then typing basics.ts.

Step 3: Write Your TypeScript Code

  • Open basics.ts and write the following code:
    let name = 'Raghav';
    console.log(name);
    
  • This code initializes a variable name with the value 'Raghav' and logs it to the console.

Step 4: Open the Terminal in VS Code

  • To open the integrated terminal in VS Code, use the shortcut Ctrl + `` (backtick) or navigate to View>Terminal`.

Step 5: Compile Your TypeScript Code

  • In the terminal, run the command to compile your TypeScript file:
    tsc basics.ts
    
  • This command converts your TypeScript code into JavaScript, creating a new file named basics.js.

Step 6: Verify the JavaScript File

  • Check your project folder to ensure that basics.js has been created. This file contains the JavaScript equivalent of your TypeScript code.

Step 7: Run Your Compiled JavaScript Code

  • Execute the JavaScript file using Node.js with the following command:
    node basics.js
    
  • You should see the output Raghav in the terminal.

Step 8: Exporting Variables

  • To make your variable available for use in other files, add an export statement at the top of basics.ts:
    export let name = 'Raghav';
    

Step 9: Enable Automatic Compilation

  • To compile your TypeScript file automatically whenever changes are made, use the following command:
    tsc basics.ts --watch
    
  • This command keeps the TypeScript compiler running in watch mode, automatically recompiling the code as you save changes.

Conclusion

Congratulations! You have successfully created and run your first TypeScript program. You learned how to set up a project, write TypeScript code, compile it to JavaScript, and execute it. As you continue your TypeScript journey, consider exploring more complex concepts and features of the language. Happy coding!