CODY ← Back to Courses
TS

TypeScript — JavaScript with Types

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. It adds static typing, interfaces, and modern features to catch errors early.

Static Typing Better Tooling Modern JS

What is TypeScript?

TypeScript adds static types to JavaScript, catching errors at compile time instead of runtime. It's used by millions of developers for large-scale applications.

typescript vs javascript
// JavaScript — runtime error
function greet(name) {
  return "Hello " + name;
}
greet(42);  // Works, but "Hello 42" — unintended!

// TypeScript — compile-time error
function greet(name: string): string {
  return `Hello ${name}`;
}
greet(42);  // ❌ Argument of type 'number' is not assignable to parameter of type 'string'

🔒 Type Safety

Catch type-related bugs before your code runs. No more "undefined is not a function" in production.

💡 Better IDE Support

Autocomplete, refactoring, and navigation work perfectly with typed code.

🔄 Compiles to JS

TypeScript code compiles to plain JavaScript that runs anywhere JS runs — browsers, Node.js, Deno.

Basic Types

TypeScript provides a rich set of primitive and complex types to describe your data.

TypeExampleDescription
string"hello"Text values
number42, 3.14All numbers (integers and floats)
booleantrue / falseTrue/false values
arraynumber[] or Array<string>List of values
tuple[string, number]Fixed-length array with specific types
enumenum Color { Red, Green }Named constants
anylet data: anyOpt-out of type checking (use sparingly)
unknownlet data: unknownType-safe alternative to any
voidfunction log(): voidNo return value
null / undefinedlet x: nullEmpty or uninitialized values
type annotations
let name: string = "Alice";
let age: number = 30;
let isStudent: boolean = false;
let hobbies: string[] = ["coding", "reading"];

// Tuple
let user: [string, number] = ["Alice", 30];

// Union types
let id: string | number = "abc123";
id = 456;  // also valid

// Type alias
type UserId = string | number;

Interfaces

Interfaces define the shape of objects. They're a powerful way to describe contracts in your code.

defining interfaces
interface User {
  id: number;
  name: string;
  email?: string;  // optional property
  readonly createdAt: Date;  // cannot be changed after creation
  greet(): string;
}

const alice: User = {
  id: 1,
  name: "Alice",
  createdAt: new Date(),
  greet() {
    return `Hello, I'm ${this.name}`;
  }
};

// Extending interfaces
interface Admin extends User {
  permissions: string[];
  isSuperAdmin: boolean;
}
💡 Interface vs Type: Use interfaces for objects that can be extended (open). Use type aliases for unions, tuples, and complex types. Both are powerful — choose what fits.

Functions & Types

TypeScript lets you define function parameters and return types. You can also create function overloads for multiple call signatures.

typed functions
// Basic function with types
function add(a: number, b: number): number {
  return a + b;
}

// Arrow function with type
const multiply = (a: number, b: number): number => a * b;

// Function type alias
type MathOperation = (a: number, b: number) => number;

const divide: MathOperation = (x, y) => x / y;

// Optional parameters
function greet(name: string, title?: string): string {
  return title ? `Hello, ${title} ${name}` : `Hello, ${name}`;
}

// Default parameters
function createUser(name: string, age: number = 18): User {
  return { id: 1, name, age };
}
▶ INTERACTIVE — TypeScript Demo
// This simulates TypeScript type checking interface Person { name: string; age: number; } function describe(p: Person): string { return `${p.name} is ${p.age} years old`; } const alice: Person = { name: "Alice", age: 30 }; console.log(describe(alice));

Classes & Access Modifiers

TypeScript adds object-oriented features like public, private, protected, and abstract classes.

classes in typescript
class Animal {
  private secret: string;  // only accessible within class
  protected species: string;  // accessible in subclasses
  public name: string;  // accessible everywhere

  constructor(name: string, species: string) {
    this.name = name;
    this.species = species;
    this.secret = "hidden";
  }

  public makeSound(): void {
    console.log(`${this.name} makes a sound`);
  }
}

class Dog extends Animal {
  constructor(name: string) {
    super(name, "canine");
  }
  
  bark(): void {
    console.log(`${this.name} barks!`);
    // console.log(this.secret); ❌ private — error
    console.log(this.species);  // ✅ protected — ok
  }
}

const buddy = new Dog("Buddy");
buddy.bark();

Generics

Generics allow you to create reusable components that work with any type while maintaining type safety.

generic functions
// Generic identity function
function identity<T>(arg: T): T {
  return arg;
}

const num = identity<number>(42);
const str = identity("hello");  // type inference

// Generic interface
interface Box<T> {
  value: T;
  unwrap(): T;
}

const stringBox: Box<string> = {
  value: "secret",
  unwrap() { return this.value; }
};

// Generic constraints
interface Lengthwise {
  length: number;
}

function logLength<T extends Lengthwise>(arg: T): T {
  console.log(arg.length);
  return arg;
}

logLength("hello");  // works
logLength([1, 2, 3]);  // works
// logLength(42); ❌ number doesn't have .length

Utility Types

TypeScript provides built-in utility types to transform existing types — saving you from writing repetitive code.

common utility types
interface User {
  id: number;
  name: string;
  email: string;
  password: string;
}

// Partial — all properties optional
type PartialUser = Partial<User>;
// { id?: number; name?: string; ... }

// Pick — select specific properties
type UserPreview = Pick<User, "id" | "name">;

// Omit — exclude properties
type PublicUser = Omit<User, "password">;

// Readonly — make all properties immutable
type ReadonlyUser = Readonly<User>;

// Record — create a typed object map
type RoleMap = Record<string, string[]>;
const permissions: RoleMap = {
  admin: ["read", "write", "delete"],
  user: ["read"]
};

Configuration (tsconfig.json)

The tsconfig.json file controls how TypeScript compiles your code. Here are the most important options.

tsconfig.json
{
  "compilerOptions": {
    /* Language and Environment */
    "target": "ES2020",           // Output JavaScript version
    "module": "commonjs",          // Module system
    "lib": ["ES2020", "DOM"],    // Available libraries
    
    /* Type Checking */
    "strict": true,                // Enable all strict checks
    "noImplicitAny": true,        // Error on implicit any
    "strictNullChecks": true,    // null and undefined are separate
    
    /* Modules */
    "rootDir": "./src",           // Source directory
    "outDir": "./dist",           // Output directory
    
    /* Emit */
    "sourceMap": true,             // Generate source maps for debugging
    "removeComments": true        // Remove comments from output
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist"]
}
🚀 Pro Tip: Start with "strict": true — it enables the most useful type checks and will save you from many bugs.

🛠 Project: Type-safe Todo App

Build a simple todo application with TypeScript. This project combines interfaces, types, and DOM manipulation with full type safety.

todo.ts
// Define types
interface Todo {
  id: number;
  text: string;
  completed: boolean;
  createdAt: Date;
}

type FilterType = "all" | "active" | "completed";

class TodoApp {
  private todos: Todo[] = [];
  private nextId: number = 1;
  private filter: FilterType = "all";

  constructor(private storageKey: string) {
    this.load();
  }

  addTodo(text: string): void {
    if (!text.trim()) return;
    
    const newTodo: Todo = {
      id: this.nextId++,
      text: text.trim(),
      completed: false,
      createdAt: new Date()
    };
    
    this.todos.push(newTodo);
    this.save();
  }

  toggleTodo(id: number): void {
    const todo = this.todos.find(t => t.id === id);
    if (todo) {
      todo.completed = !todo.completed;
      this.save();
    }
  }

  deleteTodo(id: number): void {
    this.todos = this.todos.filter(t => t.id !== id);
    this.save();
  }

  getFilteredTodos(): Todo[] {
    switch (this.filter) {
      case "active":
        return this.todos.filter(t => !t.completed);
      case "completed":
        return this.todos.filter(t => t.completed);
      default:
        return [...this.todos];
    }
  }

  setFilter(filter: FilterType): void {
    this.filter = filter;
  }

  private save(): void {
    localStorage.setItem(this.storageKey, JSON.stringify(this.todos));
  }

  private load(): void {
    const data = localStorage.getItem(this.storageKey);
    if (data) {
      this.todos = JSON.parse(data);
      this.nextId = Math.max(...this.todos.map(t => t.id), 0) + 1;
    }
  }
}

// Initialize app
const app = new TodoApp("todos");
🎯 Challenge: Add due dates to todos! Extend the Todo interface with `dueDate?: Date` and create a new filter for "overdue" tasks.