Skip to content

TypeScript Tutorial

Official Documentation

This tutorial is based on the official TypeScript documentation. For the most up-to-date information, visit: https://www.typescriptlang.org/docs/

Welcome to the comprehensive TypeScript tutorial! Learn how to write type-safe JavaScript at scale.

What is TypeScript?

TypeScript is JavaScript with superpowers. It adds optional static typing to JavaScript, which helps you catch errors before your code runs.

Think of it this way:

  • JavaScript: You write code, run it, and discover errors
  • TypeScript: You write code, see errors immediately in your editor, fix them, then run
typescript
// JavaScript - This runs but causes problems
function greet(name) {
    return `Hello, ${name.toUpperCase()}!`;
}
greet(123); // Runtime error! 123 doesn't have toUpperCase()

// TypeScript - This shows an error BEFORE you run it
function greet(name: string): string {
    return `Hello, ${name.toUpperCase()}!`;
}
greet(123); // ❌ Error: Argument of type 'number' is not assignable to type 'string'
greet("John"); // ✅ Works perfectly: "Hello, JOHN!"

Why Should You Learn TypeScript?

The Problem TypeScript Solves

javascript
// Without TypeScript - Common bugs in JavaScript
function calculateTotal(items) {
    let total = 0;
    for (let item of items) {
        total += item.price * item.quanity; // Typo: "quanity" instead of "quantity"
    }
    return total;
}

// This runs without error but gives wrong results!
// You might not notice until production 😱
typescript
// With TypeScript - Errors caught immediately
interface CartItem {
    name: string;
    price: number;
    quantity: number;
}

function calculateTotal(items: CartItem[]): number {
    let total = 0;
    for (let item of items) {
        total += item.price * item.quanity; // ❌ Error: Property 'quanity' does not exist
        total += item.price * item.quantity; // ✅ Correct!
    }
    return total;
}

Benefits at a Glance

BenefitWhat It MeansExample
Catch Errors EarlyFind bugs before running codeTypos, wrong types, missing properties
Better AutocompleteYour editor knows what's availableType user. and see all properties
Self-DocumentingTypes explain what code expectsfunction greet(name: string) is clear
Safer RefactoringRename with confidenceChange a property name, see all affected code
Team CollaborationEveryone understands the data shapesInterfaces define contracts

How TypeScript Works

┌─────────────────┐     ┌─────────────────┐     ┌─────────────────┐
│   Your Code     │     │   TypeScript    │     │   JavaScript    │
│   (.ts files)   │ ──▶ │   Compiler      │ ──▶ │   (.js files)   │
│                 │     │   (tsc)         │     │                 │
└─────────────────┘     └─────────────────┘     └─────────────────┘


                    ┌─────────────────┐
                    │  Type Errors    │
                    │  (if any)       │
                    └─────────────────┘

Important: TypeScript is converted to JavaScript before it runs. Browsers and Node.js only run JavaScript!

Tutorial Structure

🟢 Beginner Level

Start here if you're new to TypeScript:

LessonWhat You'll Learn
BasicsTypes, variables, type annotations - the foundation
FunctionsHow to type function parameters and returns
Objects & InterfacesDefining shapes for your data

🟡 Intermediate Level

Ready to level up? Learn these powerful features:

LessonWhat You'll Learn
ClassesObject-oriented programming with types
GenericsReusable, type-safe code
Type ManipulationTransform and combine types

🔴 Advanced Level

Master TypeScript with these advanced topics:

LessonWhat You'll Learn
ModulesOrganize code across files
DecoratorsMetaprogramming features
Declaration FilesType definitions for libraries
Advanced PatternsProfessional patterns and practices

Prerequisites

Before starting, you should have:

  • Basic JavaScript knowledge - variables, functions, arrays, objects
  • Familiarity with ES6+ - arrow functions, destructuring, template literals
  • Node.js installed - Download here
  • A code editor - VS Code is recommended (best TypeScript support)

New to JavaScript?

If you're not comfortable with JavaScript yet, check out our JavaScript Tutorial first!

Getting Started

Step 1: Install TypeScript

Open your terminal and run:

bash
# Install TypeScript globally (available everywhere)
npm install -g typescript

# Verify installation
tsc --version
# Should show something like: Version 5.x.x

Step 2: Create Your First TypeScript File

Create a new file called hello.ts:

typescript
// hello.ts

// This is a type annotation - we're saying "name must be a string"
function greet(name: string): string {
    return `Hello, ${name}!`;
}

// TypeScript knows this is correct
const message = greet("World");
console.log(message);

// Try uncommenting this line - you'll see an error!
// greet(123);

Step 3: Compile and Run

bash
# Compile TypeScript to JavaScript
tsc hello.ts

# This creates hello.js - run it with Node
node hello.js
# Output: Hello, World!

Step 4: See TypeScript in Action

Try adding this code to see type checking:

typescript
// This will show an error in your editor immediately!
function add(a: number, b: number): number {
    return a + b;
}

add(5, "10"); // ❌ Error: Argument of type 'string' is not assignable to type 'number'
add(5, 10);   // ✅ Works: returns 15

Setting Up a Real Project

For real projects, you'll want a configuration file:

bash
# Create a new folder
mkdir my-ts-project
cd my-ts-project

# Initialize npm
npm init -y

# Install TypeScript locally
npm install --save-dev typescript

# Create TypeScript config
npx tsc --init

This creates tsconfig.json:

json
{
    "compilerOptions": {
        "target": "ES2020",           // JavaScript version to output
        "module": "commonjs",          // Module system
        "strict": true,                // Enable all strict checks
        "esModuleInterop": true,       // Better import compatibility
        "skipLibCheck": true,          // Skip checking .d.ts files
        "forceConsistentCasingInFileNames": true,
        "outDir": "./dist",            // Output folder
        "rootDir": "./src"             // Source folder
    },
    "include": ["src/**/*"],
    "exclude": ["node_modules"]
}

Project structure:

my-ts-project/
├── src/
│   └── index.ts      ← Your TypeScript code
├── dist/             ← Compiled JavaScript (generated)
├── package.json
└── tsconfig.json

TypeScript vs JavaScript Comparison

Before (JavaScript)

javascript
// You have no idea what shape 'user' should be
function displayUser(user) {
    // This might crash if user is null
    // Or if user.name doesn't exist
    console.log(user.name.toUpperCase());
    console.log(`Age: ${user.age}`);
}

// Easy to make mistakes
displayUser({ nam: "John", age: 30 }); // Typo in 'name' - no error!
displayUser(null); // Crashes at runtime!

After (TypeScript)

typescript
// Clear definition of what a User looks like
interface User {
    name: string;
    age: number;
    email?: string; // Optional property
}

// TypeScript knows exactly what to expect
function displayUser(user: User): void {
    console.log(user.name.toUpperCase());
    console.log(`Age: ${user.age}`);
}

displayUser({ nam: "John", age: 30 }); // ❌ Error: 'nam' doesn't exist on type 'User'
displayUser(null); // ❌ Error: Argument of type 'null' is not assignable
displayUser({ name: "John", age: 30 }); // ✅ Works perfectly!

Common TypeScript Syntax Cheat Sheet

typescript
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// BASIC TYPES
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
let name: string = "John";
let age: number = 30;
let isActive: boolean = true;
let items: string[] = ["a", "b", "c"];

// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// FUNCTIONS
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
function add(a: number, b: number): number {
    return a + b;
}

const multiply = (a: number, b: number): number => a * b;

// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// OBJECTS & INTERFACES
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
interface User {
    id: number;
    name: string;
    email?: string; // Optional
}

const user: User = { id: 1, name: "John" };

// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// UNION TYPES (this OR that)
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
let id: string | number;
id = "abc123"; // OK
id = 123;      // OK

// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// TYPE ALIASES
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
type ID = string | number;
type Status = "pending" | "active" | "completed";

VS Code Tips for TypeScript

VS Code has excellent TypeScript support built-in:

  1. Hover over variables to see their types
  2. Ctrl/Cmd + Click on a type to go to its definition
  3. F2 to rename a symbol everywhere
  4. Ctrl/Cmd + Space for autocomplete
  5. Red squiggly lines show errors before you run code

Quick Fix

When you see a red squiggly line, click on it and press Ctrl/Cmd + . to see quick fixes!

Video Tutorials

Recommended Video Resources

Learn TypeScript through these excellent video tutorials from the community.

Free Courses

CourseCreatorDescription
TypeScript Full CoursefreeCodeCamp5-hour comprehensive course
TypeScript Crash CourseTraversy Media1-hour beginner crash course
TypeScript Tutorial for BeginnersProgramming with Mosh1-hour beginner tutorial
TypeScript in 100 SecondsFireshipQuick 100-second explanation

Official Resources

ResourceDescription
TypeScript HandbookOfficial TypeScript documentation
TypeScript PlaygroundInteractive TypeScript editor

Topic-Specific Videos

TopicVideoDuration
GenericsTypeScript Generics~20 min
Interfaces vs TypesInterface vs Type~15 min
Utility TypesUtility Types~25 min
Advanced PatternsAdvanced TypeScript~40 min

What's Next?

Ready to start learning? Begin with the basics:

Start with TypeScript Basics →

You'll learn:

  • How to add types to variables
  • All the basic types (string, number, boolean, etc.)
  • How TypeScript infers types automatically
  • Arrays, tuples, and enums
  • Union types and type aliases

Let's begin your TypeScript journey!