TYPE YOUR
WAY TO SAFETY

// JavaScript that scales.

JAVASCRIPT WITH GUARDS.

TypeScript adds static typing to JavaScript, catching errors at compile time instead of runtime. It's JavaScript that self-documents, refactors safely, and scales with your project.

WHY TYPESCRIPT?

TypeScript is JavaScript with syntax for types. It helps you catch mistakes early through type checking and makes your code more maintainable. IDEs provide better autocomplete, refactoring, and inline documentation.

ADOPT TYPESCRIPT.

Major companies like Microsoft, Google, and Airbnb use TypeScript. It powers VS Code, Angular, and countless enterprise applications. Type errors are cheaper to fix than runtime bugs.

BEGIN YOUR JOURNEY →

// The Path to Mastery

12 lessons. Complete TypeScript control.

LESSON 01

Introduction to TypeScript

Install TypeScript and understand why types matter.

Beginner
LESSON 02

Basic Types

Learn string, number, boolean, arrays, and tuples.

Beginner
LESSON 03

Type Inference

Understand how TypeScript infers types automatically.

Beginner
LESSON 04

Functions & Types

Type function parameters, returns, and arrow functions.

Beginner
LESSON 05

Interfaces

Define object shapes and contracts with interfaces.

Beginner
LESSON 06

Type Aliases

Create reusable type definitions with aliases.

Intermediate
LESSON 07

Union & Intersection

Combine types with unions and intersections.

Intermediate
LESSON 08

Classes

Type classes with access modifiers and inheritance.

Intermediate
LESSON 09

Generics

Write reusable, type-safe code with generics.

Advanced
LESSON 10

Utility Types

Master built-in types like Partial, Required, Pick, Omit.

Advanced
LESSON 11

Type Guards

Narrow types with custom type predicates.

Advanced
LESSON 12

Declaration Files

Create .d.ts files and work with untyped JavaScript.

Advanced

// Why TypeScript

TypeScript was created by Microsoft in 2012 and released as open source in 2014. It was designed to address the challenges of building large JavaScript applications.

TypeScript is a superset of JavaScript that compiles to plain JavaScript. It adds optional static typing, classes, interfaces, and modules. Any valid JavaScript is valid TypeScript.

The TypeScript compiler (tsc) transforms TypeScript code into JavaScript that runs in any browser or Node.js environment. It provides excellent tooling support in VS Code and other editors.

The future of JavaScript is typed. Own it.

// Tools & References

📖 TypeScript Docs

Official Documentation

typescriptlang.org

📦 DefinitelyTyped

Type Definitions

definitelytyped.org

🎮 TypeScript Playground

Try TypeScript Online

playground

🔰 TSConfig Reference

Compiler Options

tsconfig

// Introduction to TypeScript

×

What is TypeScript?

TypeScript is JavaScript with syntax for types. It helps you catch errors before your code runs. TypeScript compiles to plain JavaScript that works in any browser or Node.js environment.

Why TypeScript?

  • Type Safety: Catch errors at compile time
  • Better IDE Support: Autocomplete, refactoring, inline docs
  • Self-Documenting: Types serve as documentation
  • Modern Features: Use latest JS features
  • Gradual Adoption: Can be added incrementally
HISTORY: TypeScript was created by Microsoft in 2012, led by Anders Hejlsberg (creator of C#). It's now one of the most popular programming languages.

Installing TypeScript

$ npm install -g typescript # Install globally $ tsc --version Version 5.3.x

Your First TypeScript

// hello.ts const message: string = "Hello, TypeScript!"; console.log(message);

Compile & Run

$ tsc hello.ts # Creates hello.js $ node hello.js Hello, TypeScript!

tsconfig.json

{ "compilerOptions": { "target": "ES2020", "module": "commonjs", "strict": true, "outDir": "./dist" } }

Quiz

1. TypeScript compiles to _____ .

2. Who created TypeScript?

// Basic Types

×

JavaScript Types

let name: string = "Alice"; let age: number = 25; let isActive: boolean = true; // Arrays let numbers: number[] = [1, 2, 3]; let names: Array<string> = ["a", "b"];

Special Types

// Any - opt out of type checking let anything: any = "hello"; anything = 42; // Unknown - safer any let unknown: unknown = "hello"; if (typeof unknown === "string") { let str: string = unknown; // OK } // Void - no return function log(msg: string): void { console.log(msg); } // Never - never returns function fail(): never { throw new Error("Failed"); }

Tuples

// Fixed-length arrays with specific types let coord: [number, number] = [10, 20]; let user: [string, number] = ["Alice", 25]; // Optional elements let optional: [string, number?] = ["hello"];

Enums

enum Color { Red = "RED", Green = "GREEN", Blue = "BLUE" } let c: Color = Color.Red; // Numeric enum (default) enum Direction { Up, // 0 Down, // 1 Left, // 2 Right // 3 }

Quiz

1. What type opt out of type checking?

2. What type represents a fixed-size array?

// Type Inference

×

How Inference Works

TypeScript infers types when you don't specify them:

// Type is inferred from value let x = 10; // number let y = "hello"; // string let z = [1, 2]; // number[] // Return type inferred function add(a: number, b: number) { return a + b; // inferred as number }

Contextual Typing

// Type inferred from context document.addEventListener("click", (e) => { e.preventDefault(); // e is MouseEvent });

Best Common Type

// Infers number[] | string[] let arr = [0, 1, 2]; // With different types - union let mixed = [0, "a", 2]; // (string | number)[]

When to Explicitly Type

// Function parameters need explicit types function greet(name: string): string { return `Hello, ${name}!`; } // Return type often inferred, but can specify function parse(str: string): number { return Number(str); }

Quiz

1. TypeScript infers types when _____ are not specified.

// Functions & Types

×

Function Types

// Parameter and return types function add(a: number, b: number): number { return a + b; } // Optional parameters function greet(name: string, greeting?: string): string { return greeting ? `${greeting}, ${name}!` : `Hello, ${name}!`; }

Arrow Functions

// Arrow function with types const multiply = (a: number, b: number): number => a * b; // Type annotation for function variable let calculate: (a: number, b: number) => number; calculate = (a, b) => a + b;

Default & Rest Parameters

// Default parameters function createUser(name: string, role: string = "user"): string { return `${name} is a ${role}`; } // Rest parameters function sum(...numbers: number[]): number { return numbers.reduce((a, b) => a + b, 0); }

Overloads

function parse(input: string): number; function parse(input: number): string; function parse(input: string | number): number | string { if (typeof input === "string") { return Number(input); } return input.toString(); }

Quiz

1. What symbol makes a parameter optional?

2. What collects remaining arguments into an array?

// Interfaces

×

Defining Interfaces

interface User { id: number; name: string; email: string; isActive?: boolean; // optional } const user: User = { id: 1, name: "Alice", email: "alice@example.com" };

Readonly Properties

interface Config { readonly apiKey: string; readonly version: string; } const config: Config = { apiKey: "abc123", version: "1.0" }; config.apiKey = "new"; // Error!

Method Signatures

interface Calculator { add(a: number, b: number): number; subtract(a: number, b: number): number; } const calc: Calculator = { add: (a, b) => a + b, subtract: (a, b) => a - b };

Extending Interfaces

interface Person { name: string; } interface Employee extends Person { employeeId: number; department: string; }

Interface vs Type

// Interface - better for objects interface Point { x: number; y: number; } // Type - better for unions/primitives type ID = string | number;

Quiz

1. What makes a property unchangeable?

// Type Aliases

×

Creating Type Aliases

type ID = string | number; type User = { id: ID; name: string; }; type Status = "pending" | "active" | "completed";

Aliasing Functions

type Callback = (data: string) => void; function fetch(callback: Callback) { callback("data"); }

Aliased Unions

type Result<T> = | { success: true; data: T } | { success: false; error: string }; const ok: Result<string> = { success: true, data: "hello" }; const fail: Result<string> = { success: false, error: "oops" };

Quiz

1. What keyword creates a type alias?

// Union & Intersection

×

Union Types

// Value can be one of several types let id: string | number; id = "abc"; id = 123; // Narrowing with typeof function format(value: string | number): string { if (typeof value === "string") { return value.toUpperCase(); } return value.toFixed(2); }

Literal Types

type Direction = "north" | "south" | "east" | "west"; let dir: Direction = "north";

Intersection Types

type A = { a: string }; type B = { b: number }; type C = A & B; const c: C = { a: "hello", b: 42 };

Quiz

1. What symbol creates a union type?

2. What symbol combines types?

// Classes

×

Basic Class

class Person { name: string; age: number; constructor(name: string, age: number) { this.name = name; this.age = age; } greet(): void { console.log(`Hello, I'm ${this.name}`); } }

Access Modifiers

class BankAccount { public readonly id: string; private balance: number; protected owner: string; constructor(id: string, balance: number) { this.id = id; this.balance = balance; } public deposit(amount: number): void { this.balance += amount; } }

Inheritance

class Employee extends Person { employeeId: number; constructor(name: string, age: number, id: number) { super(name, age); this.employeeId = id; } greet(): void { console.log(`I'm ${this.name}, employee #${this.employeeId}`); } }

Abstract Classes

abstract class Animal { abstract makeSound(): void; move(): void { console.log("Moving..."); } }

Quiz

1. What modifier restricts access to the class?

// Generics

×

Generic Functions

function identity<T>(value: T): T { return value; } const num = identity(42); // number const str = identity("hello"); // string

Generic Interfaces

interface Container<T> { value: T; getValue(): T; } const box: Container<number> = { value: 10, getValue() { return this.value; } };

Constraints

interface HasLength { length: number; } function logLength<T extends HasLength>(item: T): void { console.log(item.length); } logLength("hello"); // OK - strings have length logLength([1, 2]); // OK - arrays have length logLength(42); // Error!

Quiz

1. What limits a generic type?

// Utility Types

×

Partial & Required

interface User { id: number; name: string; email: string; } // All properties optional type PartialUser = Partial<User>; // All properties required type RequiredUser = Required<PartialUser>;

Pick & Omit

// Select specific properties type UserPreview = Pick<User, "id" | "name">; // Exclude specific properties type UserWithoutEmail = Omit<User, "email">;

Record

// Create object type with specific keys and values type UsersById = Record<string, User>; const users: UsersById = { "1": { id: 1, name: "Alice", email: "a@a.com" }, "2": { id: 2, name: "Bob", email: "b@b.com" } };

Quiz

1. What makes all properties optional?

// Type Guards

×

typeof Guards

function print(value: string | number) { if (typeof value === "string") { console.log(value.toUpperCase()); } else { console.log(value.toFixed(2)); } }

instanceof Guards

class Dog { bark(): void { console.log("Woof!"); } } class Cat { meow(): void { console.log("Meow!"); } } function makeSound(animal: Dog | Cat) { if (animal instanceof Dog) { animal.bark(); } else { animal.meow(); } }

Custom Type Predicates

interface Fish { swim(): void; } interface Bird { fly(): void; } function isFish(animal: Fish | Bird): animal is Fish { return (Fish.prototype.isPrototypeOf(animal)); }

Quiz

1. What narrows union types in TypeScript?

// Declaration Files

×

.d.ts Files

Declaration files provide type information for JavaScript:

// math.d.ts declare function add(a: number, b: number): number; declare const PI: number; export { add, PI };

Ambient Variables

// globals.d.ts declare const MY_API_KEY: string; declare interface Window { myPlugin: any; }

DefinitelyTyped

$ npm install --save-dev @types/lodash # Install type definitions

Quiz

1. What file extension do type declarations use?