Your First TypeScript Program
In this page:
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
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
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
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
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
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: