Typescript Foundations / Introduction to Typescript

Writing and Compiling Typescript files

πŸ‘‰ Create a file called example.ts

// example.ts

function greet(name: string): string {
  return `Hello, ${name}`;
}

const message = greet("TypeScript");
console.log(message);

βœ… Notes:

  • The function greet expects a string argument and returns a string.

  • TypeScript will check that name is a string during compile time.


⚑ Compiling the TypeScript file

πŸ‘‰ Open your terminal and run:

tsc example.ts

βœ… This will generate a file:

example.js

πŸ‘‰ The output JavaScript will look like:

function greet(name) {
  return "Hello, " + name;
}
const message = greet("TypeScript");
console.log(message);

➑ Notice the types are gone! TypeScript strips types because JavaScript doesn’t support them β€” but the type checks happen during compilation.


βš™οΈ Running the compiled JavaScript

Run your JS file using Node (or in a browser):

node example.js

πŸ” Optional: Watch mode

If you want TypeScript to compile automatically whenever you save your file:

tsc example.ts --watch

Now every time you save example.ts, it re-compiles automatically.


πŸ›  Using tsconfig.json for multi-file projects

If you have multiple .ts files:

1️⃣ Generate a config file:

tsc --init

2️⃣ Edit tsconfig.json (optional, e.g., set "outDir": "./dist")

3️⃣ Compile the whole project:

tsc

βœ… All TypeScript files in the project will be compiled according to tsconfig.json rules.


✨ Summary of steps

Step

Command

Write .ts file

(e.g., example.ts)

Compile

tsc example.ts

Run JS

node example.js

Watch mode

tsc example.ts --watch

Multi-file project

tsc --init, then tsc