First TypeScript Program Hello World Example

Getting started with TypeScript is simple and straightforward. One of the best ways to begin is by writing a "Hello World" program. This classic example helps you understand the basics of TypeScript syntax and the compilation process. In this guide, we'll walk you through creating and running your first TypeScript program.

Prerequisites

Before you start, make sure you have TypeScript installed on your system. You also need Node.js and npm (Node Package Manager) to compile and run your TypeScript code. If you haven't installed TypeScript yet, follow the installation guide to set it up.

Creating Your TypeScript File

First, create a new folder for your project and navigate to it using the terminal:

mkdir hello-world-ts
cd hello-world-ts

Next, create a new TypeScript file named hello.ts:

echo "console.log('Hello, TypeScript!');" > hello.ts

Writing the Hello World Program

In your hello.ts file, write the following code:

console.log('Hello, TypeScript!');

This simple program logs the message "Hello, TypeScript!" to the console.

Compiling TypeScript to JavaScript

TypeScript needs to be compiled into JavaScript before it can be executed. Use the TypeScript compiler (tsc) to compile your TypeScript file:

npx tsc hello.ts

This command generates a JavaScript file named hello.js in the same directory. You can verify the compilation by checking the contents of the generated JavaScript file:

cat hello.js

The output should look like this:

console.log('Hello, TypeScript!');

Running the JavaScript File

To see the output of your program, run the compiled JavaScript file using Node.js:

node hello.js

You should see the following message printed to the console:

Hello, TypeScript!

Conclusion

Congratulations! You’ve just created and executed your first TypeScript program. This basic example demonstrates how to write TypeScript code, compile it to JavaScript, and run it. As you continue to learn TypeScript, you’ll explore more advanced features and capabilities that make it a powerful tool for modern web development.