
In TypeScript, you can write “Hello, World!” in multiple ways. Here are some common methods:
1. Using console.log (Basic Output)
console.log("Hello, World!");
This prints “Hello, World!” to the console.
2. Using Type Annotations
let message: string = "Hello, World!";
console.log(message);
Here, message is explicitly typed as a string.
3. Writing to an HTML Page (document.body.innerHTML)
let message: string = "Hello, World!";
document.body.innerHTML = `<h1>${message}</h1>`;
This injects “Hello, World!” into the webpage inside an <h1> tag.
4. Using a Function with Type Annotations
function greet(): string {
return "Hello, World!";
}
console.log(greet());
This defines a function greet() that returns a string.
5. Using an Arrow Function
const greet = (): string => "Hello, World!";
console.log(greet());
This is a shorter, modern way to define the function.
6. Compiling and Running TypeScript
If you’re using a .ts file, compile it with:
tsc hello.ts
Then run the generated JavaScript file:
node hello.js

February 1, 2025