Prerequisites
- Basic understanding of JavaScript ๐
- Node.js installed on your system ๐ข
- Command line basics ๐ป
What you'll learn
- Install TypeScript globally and locally ๐ฏ
- Configure TypeScript for your project ๐ ๏ธ
- Write and run your first TypeScript program ๐
- Understand basic TypeScript workflow โจ
๐ฏ Introduction
Welcome to your TypeScript journey! ๐ In this guide, weโll walk through everything you need to get TypeScript up and running on your machine.
Youโll discover how TypeScript can transform your JavaScript development experience. Whether youโre building web applications ๐, server-side code ๐ฅ๏ธ, or libraries ๐, getting TypeScript properly set up is your first step toward writing more reliable, maintainable code.
By the end of this tutorial, youโll have TypeScript installed, configured, and youโll have written your first type-safe program! Letโs dive in! ๐โโ๏ธ
๐ Understanding TypeScript Setup
๐ค What is TypeScript?
TypeScript is like JavaScript with superpowers! ๐ฆธโโ๏ธ Think of it as JavaScript wearing a safety helmet ๐ช that protects you from common programming errors before they happen.
In technical terms, TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. This means you can:
- โจ Write safer code with type checking
- ๐ Catch errors before runtime
- ๐ก๏ธ Get better IDE support and autocomplete
- ๐ Use modern JavaScript features everywhere
๐ก Why Install TypeScript?
Hereโs why developers love TypeScript:
- Early Error Detection ๐: Find bugs during development, not in production
- Better Developer Experience ๐ป: Amazing autocomplete and refactoring tools
- Self-Documenting Code ๐: Types serve as inline documentation
- Future-Proof ๐ฎ: Use tomorrowโs JavaScript features today
Real-world example: Imagine building a user registration system ๐ค. With TypeScript, youโll know immediately if youโre passing the wrong data types, preventing crashes before users even see them!
๐ง Basic Installation and Setup
๐ Step 1: Verify Node.js Installation
First, letโs make sure you have Node.js installed:
# ๐ Check your Node.js version
node --version
# Should output something like: v18.0.0 or higher
# ๐จ Check npm version
npm --version
# Should output something like: 9.0.0 or higher
๐ก Pro Tip: If you donโt have Node.js, download it from nodejs.org. Choose the LTS version for stability! ๐ก๏ธ
๐ฏ Step 2: Install TypeScript
You have two options for installing TypeScript:
Option A: Global Installation (Recommended for beginners) ๐
# ๐ Install TypeScript globally
npm install -g typescript
# โ
Verify installation
tsc --version
# Should output: Version 5.x.x
Option B: Local Project Installation (Best practice) ๐
# ๐ Create a new project directory
mkdir my-typescript-project
cd my-typescript-project
# ๐ฏ Initialize npm project
npm init -y
# ๐ฆ Install TypeScript as dev dependency
npm install --save-dev typescript
# โจ Add to package.json scripts
# Your package.json should have:
# "scripts": {
# "tsc": "tsc"
# }
๐ ๏ธ Step 3: Initialize TypeScript Configuration
Create a TypeScript configuration file:
# ๐จ Initialize tsconfig.json
tsc --init
# ๐ Success! You'll see:
# "Created a new tsconfig.json with recommended settings"
๐ก Practical Examples
๐ Example 1: Your First TypeScript Program
Letโs create a simple greeting program:
// ๐ Create a file: hello.ts
// ๐ Define a greeting function with types
function greet(name: string, age: number): string {
return `Hello ${name}! You are ${age} years old. Welcome to TypeScript! ๐`;
}
// ๐ฏ Create a user object
interface User {
name: string;
age: number;
emoji: string;
}
const newUser: User = {
name: "Sarah",
age: 25,
emoji: "๐"
};
// ๐ Use our function
console.log(greet(newUser.name, newUser.age));
console.log(`${newUser.emoji} TypeScript is amazing!`);
Compile and run:
# ๐ ๏ธ Compile TypeScript to JavaScript
tsc hello.ts
# ๐ฎ Run the generated JavaScript
node hello.js
๐ฏ Try it yourself: Add a favoriteColor
property to the User interface!
๐ฎ Example 2: Setting Up a Real Project
Letโs create a more realistic project structure:
# ๐ Project structure
my-typescript-project/
โโโ src/
โ โโโ index.ts
โ โโโ utils/
โ โโโ calculator.ts
โโโ dist/
โโโ package.json
โโโ tsconfig.json
Configure tsconfig.json for this structure:
{
"compilerOptions": {
// ๐ฏ Output directory
"outDir": "./dist",
// ๐ Root directory of source files
"rootDir": "./src",
// ๐ก๏ธ Enable strict type checking
"strict": true,
// ๐จ Target modern JavaScript
"target": "ES2020",
"module": "commonjs",
// ๐ก Better debugging
"sourceMap": true,
// โจ Enable decorators
"experimentalDecorators": true,
// ๐ Import helpers
"esModuleInterop": true,
// ๐ฏ Skip lib check for faster builds
"skipLibCheck": true,
// ๐ Consistent casing in file names
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
Create the calculator utility:
// ๐ src/utils/calculator.ts
// ๐งฎ Simple calculator with emojis!
export class Calculator {
// โ Addition
add(a: number, b: number): number {
console.log(`โ Adding ${a} + ${b}`);
return a + b;
}
// โ Subtraction
subtract(a: number, b: number): number {
console.log(`โ Subtracting ${a} - ${b}`);
return a - b;
}
// โ๏ธ Multiplication
multiply(a: number, b: number): number {
console.log(`โ๏ธ Multiplying ${a} ร ${b}`);
return a * b;
}
// โ Division
divide(a: number, b: number): number {
if (b === 0) {
console.log(`๐ซ Cannot divide by zero!`);
throw new Error("Division by zero!");
}
console.log(`โ Dividing ${a} รท ${b}`);
return a / b;
}
}
Use it in your main file:
// ๐ src/index.ts
import { Calculator } from './utils/calculator';
// ๐ฏ Create calculator instance
const calc = new Calculator();
// ๐ฎ Let's do some math!
console.log('๐งฎ TypeScript Calculator Demo\n');
const results = {
addition: calc.add(10, 5),
subtraction: calc.subtract(20, 8),
multiplication: calc.multiply(7, 6),
division: calc.divide(100, 4)
};
console.log('\n๐ Results:');
console.log(` โ 10 + 5 = ${results.addition}`);
console.log(` โ 20 - 8 = ${results.subtraction}`);
console.log(` โ๏ธ 7 ร 6 = ${results.multiplication}`);
console.log(` โ 100 รท 4 = ${results.division}`);
console.log('\nโจ All calculations complete!');
๐ Advanced Setup Options
๐งโโ๏ธ Using Build Scripts
Add these scripts to your package.json:
{
"scripts": {
"build": "tsc",
"watch": "tsc --watch",
"dev": "tsc --watch & node dist/index.js",
"clean": "rm -rf dist",
"start": "node dist/index.js"
}
}
๐๏ธ TypeScript with Modern Tools
For advanced setups, consider these tools:
# ๐ Vite for fast development
npm create vite@latest my-app -- --template vanilla-ts
# ๐ฆ Parcel for zero-config bundling
npm install --save-dev parcel
# Create index.html that references your .ts files
# โก ESBuild for ultra-fast builds
npm install --save-dev esbuild
โ ๏ธ Common Pitfalls and Solutions
๐ฑ Pitfall 1: Module Resolution Issues
// โ Wrong - Can't find module
import { something } from 'my-module';
// Error: Cannot find module 'my-module'
// โ
Correct - Install types
npm install --save-dev @types/my-module
// Or create a declaration file
๐คฏ Pitfall 2: Forgetting to Compile
# โ Wrong - Running TypeScript directly
node src/index.ts # ๐ฅ Error!
# โ
Correct - Compile first, then run
tsc
node dist/index.js # โ
Works!
# ๐ Or use ts-node for development
npm install --save-dev ts-node
npx ts-node src/index.ts # โจ Direct execution!
๐ต Pitfall 3: Configuration Confusion
// โ Wrong - Too permissive
{
"compilerOptions": {
"strict": false, // ๐ฐ No type safety!
"any": true // ๐ซ Not a real option!
}
}
// โ
Correct - Embrace the safety!
{
"compilerOptions": {
"strict": true, // ๐ก๏ธ Maximum safety
"noImplicitAny": true, // ๐ฏ No implicit any
"strictNullChecks": true // ๐ Null safety
}
}
๐ ๏ธ Best Practices
- ๐ฏ Always Use tsconfig.json: Donโt rely on command-line flags
- ๐ Enable Strict Mode: Start strict, relax if needed
- ๐ก๏ธ Install Type Definitions: Use @types/ packages
- ๐จ Organize Your Code: Use src/ and dist/ directories
- โจ Use Modern Targets: Target ES2020 or later for modern features
๐งช Hands-On Exercise
๐ฏ Challenge: Create a TypeScript Project
Set up a complete TypeScript project with:
๐ Requirements:
- โ Proper project structure (src/, dist/)
- ๐ท๏ธ Configured tsconfig.json
- ๐ค A simple to-do type system
- ๐ Build and watch scripts
- ๐จ At least 3 TypeScript files
๐ Bonus Points:
- Add ESLint for TypeScript
- Configure path aliases
- Set up debugging in VS Code
๐ก Solution
๐ Click to see solution
# ๐ฏ Complete project setup
mkdir typescript-todo-app
cd typescript-todo-app
npm init -y
npm install --save-dev typescript @types/node
# ๐ Create structure
mkdir -p src/models src/services dist
Create tsconfig.json:
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"sourceMap": true,
"paths": {
"@models/*": ["./src/models/*"],
"@services/*": ["./src/services/*"]
}
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
Create todo model:
// ๐ src/models/todo.ts
export interface Todo {
id: string;
title: string;
completed: boolean;
emoji: string;
createdAt: Date;
}
Create todo service:
// ๐ src/services/todoService.ts
import { Todo } from '../models/todo';
export class TodoService {
private todos: Todo[] = [];
addTodo(title: string, emoji: string = '๐'): Todo {
const todo: Todo = {
id: Date.now().toString(),
title,
completed: false,
emoji,
createdAt: new Date()
};
this.todos.push(todo);
console.log(`โ
Added: ${emoji} ${title}`);
return todo;
}
listTodos(): void {
console.log('๐ Your todos:');
this.todos.forEach(todo => {
const status = todo.completed ? 'โ
' : 'โณ';
console.log(` ${status} ${todo.emoji} ${todo.title}`);
});
}
}
Update package.json:
{
"scripts": {
"build": "tsc",
"watch": "tsc --watch",
"start": "node dist/index.js",
"dev": "tsc && node dist/index.js"
}
}
๐ Key Takeaways
Youโve learned so much! Hereโs what you can now do:
- โ Install TypeScript globally or locally ๐ช
- โ Configure TypeScript projects with tsconfig.json ๐ก๏ธ
- โ Write and compile TypeScript programs ๐ฏ
- โ Set up project structure like a pro ๐
- โ Use modern TypeScript features! ๐
Remember: Getting started is the hardest part - youโve already done it! ๐
๐ค Next Steps
Congratulations! ๐ Youโve successfully set up TypeScript!
Hereโs what to do next:
- ๐ป Complete the hands-on exercise
- ๐๏ธ Create a small project to practice
- ๐ Move on to our next tutorial: TypeScript vs JavaScript
- ๐ Join the TypeScript community!
Remember: Every TypeScript expert started exactly where you are now. Keep coding, keep learning, and most importantly, have fun! ๐
Happy coding! ๐๐โจ