Writing and Compiling Your First TypeScript Program Step by step Implementation and Top 10 Questions and Answers
 .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    Last Update: April 01, 2025      10 mins read      Difficulty-Level: beginner

Writing and Compiling Your First TypeScript Program

Welcome to the world of TypeScript, a statically typed superset of JavaScript that adds enhanced features while maintaining compatibility with existing JavaScript code. If you're new to TypeScript and looking to get started, this guide will walk you through the process of writing and compiling your first TypeScript program. We'll cover everything from setting up your environment to understanding the basic syntax and features of TypeScript.

Step 1: Install Node.js and npm

First things first, ensure you have Node.js and npm (Node Package Manager) installed on your machine since TypeScript is built on Node.js. You can download the latest version of Node.js from its official website, nodejs.org. The installer includes npm, so you won't need to install it separately.

  • Download and install Node.js: Go to the Node.js website, choose the LTS (Long Term Support) version, and follow the installation instructions for your operating system.
  • Verify Installation: Open a terminal or command prompt and type the following commands to verify that Node.js and npm are correctly installed:
node -v
npm -v

You should see version numbers printed out. If these commands return an error, there might be an issue with the installation.

Step 2: Install TypeScript Globally

Now that Node.js and npm are installed, you can use npm to install TypeScript globally on your machine. Run the following command in your terminal:

npm install -g typescript

This command installs TypeScript as a global package, available anywhere on your system via command line.

  • Verify TypeScript Installation: To make sure TypeScript is installed correctly, run this command:
tsc -v

Again, you should see the version number of TypeScript.

Step 3: Create a Project Directory

It’s a good practice to organize your code in separate directories. Open your terminal or command prompt and create a new folder for your TypeScript project:

mkdir my-first-typescript-project
cd my-first-typescript-project

Navigate to your new project directory.

Step 4: Initialize a New Node.js Project

Even though we're using TypeScript for this project, initializing a Node.js project with npm will help manage dependencies and project settings in the future. Run the following command to generate a package.json file:

npm init -y

The -y flag automatically answers "yes" to all npm prompts, creating a default package.json configuration.

You can open and view this file later to manage project-specific options such as dependencies, scripts, and author information.

Step 5: Write Your First TypeScript Program

TypeScript files use the .ts extension. Let's write a simple "Hello, World!" program.

Create a new file named hello-world.ts using your preferred text editor (VSCode, Sublime Text, etc.).

Open the file and add the following lines:

function greet(name: string): string {
    return `Hello, ${name}! Welcome to TypeScript.`;
}

const personName: string = "John";
console.log(greet(personName));

Here's what this code does:

  1. Function Declaration: The greet function takes one parameter, name, which has a type of string. It returns a string.
  2. Template String: Inside the function, the greet method uses template literals (backticks `) to embed expressions within strings, making our output more dynamic.
  3. Variable Declaration and Initialization: The variable personName is declared with a type of string and assigned the value "John".
  4. Logging Output: Finally, we use console.log to print the result of calling greet(personName) to the console.

Step 6: Compile Your TypeScript Program

To run TypeScript, you need to compile it into JavaScript since browsers and Node.js don't understand TypeScript natively. This conversion is performed by the TypeScript Compiler (tsc).

In your terminal, run the following command from your project directory to compile hello-world.ts:

tsc hello-world.ts

Running this command generates a hello-world.js file in the same directory as your .ts file. The content of this file will look something like this:

function greet(name) {
    return "Hello, " + name + "! Welcome to TypeScript.";
}
var personName = "John";
console.log(greet(personName));

Notice how the TypeScript syntax got translated into valid JavaScript. Now you're ready to run your program.

Step 7: Run Your Compiled JavaScript Program

To execute the JavaScript that was produced by the TypeScript compiler, you can use Node.js. From your project directory, run this command:

node hello-world.js

You should see the following output:

Hello, John! Welcome to TypeScript.

Congratulations! You’ve just written and compiled your first TypeScript program.

Step 8: Setup tsconfig.json (Optional but Recommended)

A tsconfig.json file helps define TypeScript project settings like compiler options, include/exclude files, module systems, and more. For large projects, this setup is a best practice. Here’s how you can create tsconfig.json using tsc:

Run this command from your project directory:

tsc --init

This action will generate a tsconfig.json file with default values. Feel free to modify this file according to your needs.

For now, you don't need to make any changes unless you want to alter the default compilation behavior.

With tsconfig.json, you can compile all .ts files within the project by simply running:

tsc

When a tsconfig.json file exists in the project root, tsc compiles the entire project based on the settings defined.

Step 9: Integrate with a Code Editor (Optional but Ideal)

Integrating TypeScript with a code editor enhances your development experience by providing features like code completion, syntax highlighting, and real-time error checking. Visual Studio Code (VSCode) is popular among developers for its excellent TypeScript support.

  1. Install VSCode: You can download VSCode from code.visualstudio.com.
  2. Open Your Project: Launch VSCode, then navigate to File > Open Folder… and select your TypeScript project directory.
  3. Create TypeScript File: Inside VSCode, create a new file and save it with a .ts extension, e.g., hello-world-vsc.ts.
  4. Write Code: Add similar code to what you did earlier:
function greet(name: string): string {
    return `Hello, ${name}! Welcome to TypeScript.`;
}

const personName: string = "Jane";
console.log(greet(personName));
  1. Compile: You can compile the file directly from VSCode. Install the "TypeScript" extension if prompted, and use the integrated terminal to compile the file:
tsc hello-world-vsc.ts
  1. Execute: After successful compilation, run the generated JavaScript file:
node hello-world-vsc.js

You’ll still see the output:

Hello, Jane! Welcome to TypeScript.

But now, enjoy enhanced development tools!

Key Concepts of TypeScript Explored So Far:

  1. Static Typing: TypeScript allows you to explicitly declare variable types. In our program, we used the string type, but TypeScript supports many others like number, boolean, array, tuple, enum, any, void, unknown, and never. Static typing makes catching errors sooner possible and improves code readability and maintainability.

  2. Functions, Return Types, and Parameters: Functions in TypeScript can have specified return types and parameter types. This helps prevent incorrect usage and enhances predictability.

  3. Template Literals: Using backticks around strings allows embedding variables directly inside them using ${variableName}. This makes constructing dynamic strings simpler and less prone to errors.

  4. Compilation: TypeScript code must be compiled into JavaScript because browsers do not directly execute TypeScript.

  5. Configuration: tsconfig.json centralizes project settings and helps streamline the build process.

Conclusion

Getting started with TypeScript is straightforward, leveraging the familiarity of JavaScript while introducing static typing and other features that make your code more robust. By following these steps, you successfully set up your development environment, wrote a basic TypeScript program, compiled it into JavaScript, and ran it.

As you delve deeper into TypeScript, you'll explore more advanced concepts such as interfaces, classes, decorators, namespaces, generics, and asynchronous programming, all enhancing your ability to write complex applications confidently and efficiently.

Happy coding!