Hello World in TypeScript
Your first TypeScript program - the classic Hello World example with Docker setup
Every programming journey starts with Hello World. Let’s write our first TypeScript program.
The Code
Create a file named hello.ts:
| |
Yes, it’s that simple! This is valid JavaScript too, but let’s see what TypeScript adds.
Understanding the Code
console.log()- Prints to standard output with a newline, just like JavaScript..tsextension - Tells tools this is a TypeScript file, enabling type checking.
Running with Docker
The easiest way to run this without installing Node.js locally:
| |
Running Locally
If you have Node.js installed:
| |
Expected Output
Hello, World!
Key Concepts
- Superset of JavaScript - Any valid JS is valid TS
.tsextension - Enables TypeScript tooling and type checking- Compiles to JavaScript - TypeScript doesn’t run directly; it becomes JS
- ts-node - Convenience tool that compiles and runs in one step
- No runtime overhead - Types are erased at compile time
Adding Types
Let’s make it more TypeScript-like with explicit types:
| |
The : string is a type annotation. TypeScript can infer this type, but explicit annotations help document your code.
A Typed Function Example
| |
This demonstrates:
- Parameter types -
name: stringensures only strings are passed - Return type -
: stringafter the parentheses declares the return type - Template literals -
`Hello, ${name}!`for string interpolation
TypeScript vs. JavaScript Hello World
JavaScript version:
| |
TypeScript version:
| |
TypeScript catches the bug at compile time, before your code runs.
A More Complete Example
| |
This shows:
- Interfaces - Define the shape of objects
- Type safety - Can’t pass objects missing required properties
- Self-documenting - The interface tells you what
greetexpects
Next Steps
Continue to Variables and Types to learn about TypeScript’s powerful type system.