AI Hints
Home›Angular Tutorial›Classes, Optional and Union Types and Arrays and Generics
Angular · Lesson 13 of 120

Classes

Blueprints for objects.

⏱ 2 min read▶ Video at 15:05🎓 Free
Watch this lesson in the Angular courseWatch on YouTube ↗Full Angular course

Every Angular component, and every service, is a class. So let's be sure we understand classes in TypeScript.

  • Components are classes
  • Services are classes
  • Let's understand them

A class

A class is a blueprint for objects. It has properties, which hold data, and methods, which do things. New creates an object from the class. And this means, the current object.

keyvalue
Propertiesdata
Methodsactions
new Basket()creates an object
thisthe current object

A Basket class

Items is a private array of titles, starting empty. Add pushes a title into it. Count is a getter, so we read it like a property, without brackets. We create a basket, and add two books. Run it. The basket has two books.

main.tstypescript
class Basket {
  private items: string[] = [];

  add(title: string) {
    this.items.push(title);
  }

  get count(): number {
    return this.items.length;
  }
}

const basket = new Basket();
basket.add("Dune");
basket.add("Emma");
console.log(`Books in the basket: ${basket.count}`);
Output
Books in the basket: 2
Also uses _mode
ts

Private means private

Items is private, so only code inside the class may touch it. Here, we try to empty it from outside. Run it. TypeScript stops us. Items is private, and only accessible within class Basket.

main.tstypescript
class Basket {
  private items: string[] = [];

  add(title: string) {
    this.items.push(title);
  }

  get count(): number {
    return this.items.length;
  }
}

const basket = new Basket();
basket.add("Dune");
basket.add("Emma");
console.log(`Books in the basket: ${basket.count}`);
basket.items = [];
Output
main.ts(17,8): error TS2341: Property 'items' is private and only accessible within
class 'Basket'.
Also uses _mode
ts

Constructor shortcuts

Writing public, or private, in front of a constructor parameter creates a property, and fills it, in one go. Angular code uses this style a lot. Title is public, so we can read it. And the private price is used inside price for. Run it. Dune, and the price for three copies.

main.tstypescript
class Book {
  constructor(public title: string, private price: number) {}

  priceFor(copies: number): number {
    return this.price * copies;
  }
}

const dune = new Book("Dune", 9.99);
console.log(dune.title);
console.log(dune.priceFor(3).toFixed(2));
Output
Dune
29.97
Also uses _mode
ts

Summary

Classes have properties, methods, and getters, and private keeps data safe inside. Constructor parameters can create properties. Next, optional, and union types.

Key takeaways
  • class Basket
  • private
  • constructor(public title)
Next up: Optional and Union Types — maybe, and one of several