← Back to TypeScript Course | Chapter 1: Introduction to TypeScript | Lesson 4 of 7

Your First TypeScript Program

A first TypeScript program can be very small, such as printing a message to the console. The usual workflow is to write the program in a .ts file, compile it into JavaScript, and then run the generated JavaScript.

Writing Hello World

The classic first program displays a Hello World message using console.log, just like plain JavaScript. TypeScript lets you write this familiar statement unchanged while giving you the option to add type information as the program grows.

Example: Writing Hello World

typescript
console.log("Hello, World!");

Using Variables

Variables let a program store information for later use, and TypeScript can attach a type annotation to make the intended kind of value explicit. Once a variable is typed, assigning a value of the wrong kind is caught before the code ever runs.

Example: Using Variables

typescript
let username: string = "Riya";
// username = 42; // TypeScript rejects assigning the wrong type
console.log(username);

Creating a Function

Functions group reusable instructions together, and TypeScript lets you specify the types of each parameter and the value the function returns. This means a typo in an argument, like passing a string where a number is expected, is flagged immediately by the compiler.

Example: Creating a Function

typescript
function greet(name: string): string {
  return `Hello, ${name}!`;
}
console.log(greet("Sam"));

Using Arrays

Arrays store multiple values in one variable, and TypeScript can specify the type of values an array is expected to contain using syntax like number[]. Attempting to push a mismatched value into a typed array produces a compile-time error.

Example: Using Arrays

typescript
let scores: number[] = [10, 20, 30];
// scores.push("high"); // rejected: string is not a number
scores.push(40);
console.log(scores);

Compiling and Running

After writing a TypeScript file, the tsc compiler transforms it into plain JavaScript by stripping out the type annotations. The generated .js file can then be run with any standard JavaScript runtime such as Node.js or a browser.

Example: Compiling and Running

typescript
let message: string = "Ready to compile";
console.log(message);
// tsc strips ": string" and produces a plain .js file to run with node
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.