AI Hints
TypeScript · Lesson 43 of 120

Classes

Blueprints.

⏱ 2 min read▶ Video at 34:20🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

A class is a blueprint for objects. It bundles data, called properties, with functions that use it, called methods. TypeScript types both.

Classes
From the video: Classes
  • A blueprint
  • Properties and methods
  • Both typed

A Basket class

The basket has a typed list of items. The constructor sets the owner. Add puts an item in, and total adds up the prices. We make a basket with new. Run it.

app.tstypescript
class Basket {
  owner: string;
  items: { name: string; price: number }[] = [];

  constructor(owner: string) {
    this.owner = owner;
  }

  add(name: string, price: number): void {
    this.items.push({ name, price });
  }

  total(): number {
    return this.items.reduce((sum, i) => sum + i.price, 0);
  }
}

const basket = new Basket("Priya"); basket.add("Helmet", 40); basket.add("Lights", 25);
console.log(basket.owner, "owes £" + basket.total());
Output
Priya owes £65

Summary

Classes bundle typed properties and methods, and new makes an object. Next, access modifiers.

Key takeaways
  • class
  • constructor
  • new
Next up: Access Modifiers — public, private, protected