Your First TypeScript Program: Hello, TypeScript!

November 28, 2023

Welcome to your first lesson in TypeScript! Whether you are a seasoned programmer or just starting out, this post will guide you through writing your first TypeScript program. TypeScript is a superset of JavaScript, meaning it builds upon the syntax and features of JavaScript while adding additional functionality.

Before we dive into coding, let’s cover the basics of TypeScript. It is a strongly typed language, which means that variables and values have specific types. This allows for better error checking and helps catch bugs before they become a problem. TypeScript also supports object-oriented programming, making it a powerful choice for building complex applications.

To get started, you will need to have Node.js and a code editor installed on your computer. Once you have those set up, you can begin writing your first TypeScript program. Let’s begin by creating a new file called ‘hello.ts’ and opening it in your code editor.

The first thing we need to do is add a type annotation to our variable. This tells TypeScript what type of value we are assigning to the variable. In this case, we will use the ‘string’ type for our ‘message’ variable, which will hold the string ‘Hello, TypeScript!’. Here’s what our code looks like:


let message: string = 'Hello, TypeScript!';
console.log(message);

Next, we need to compile our TypeScript code into JavaScript. This is done using the TypeScript compiler, which can be installed globally using the command ‘npm install -g typescript’. Once the compiler is installed, navigate to the directory where your ‘hello.ts’ file is located and run the command ‘tsc hello.ts’. This will generate a new file called ‘hello.js’ that contains the compiled JavaScript code.

Now, let’s run our program and see the output. In your terminal, type ‘node hello.js’ and you should see ‘Hello, TypeScript!’ printed to the console. Congratulations, you have successfully written and compiled your first TypeScript program!

As a final step, let’s modify our code to use a function instead. This will give us a better understanding of how TypeScript handles functions. Here’s our updated code:


function greet(name: string) {
  let message: string = 'Hello, ' + name + '!';
  console.log(message);
}

greet('TypeScript');

Notice that we have added a parameter ‘name’ to our function and used string concatenation to create our message. Now, when we run our program with ‘node hello.js’, we will see ‘Hello, TypeScript!’ printed to the console.

That’s it for your first TypeScript program! You have learned about basic syntax, type annotations, and compiling TypeScript into JavaScript. Keep practicing and exploring the many features of TypeScript to enhance your coding skills. Happy coding!