We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Classes

Classes in TypeScript work mostly the same way that they do in JavaScript, but with the added benefit of static typing. One of the biggest differences is that you'll see type annotations on all the class properties at the top level of the class declaration.

class Hero {
  name: string;
  health: number;

  constructor(name: string, health: number) {
    this.name = name;
    this.health = health;
  }

  attack(damage: number): void {
    console.log(`${this.name} attacks for ${damage} damage!`);
  }

  getHealth() {
    return this.health;
  }
}

// Create an instance
const geralt = new Hero("Geralt", 100);
geralt.attack(25);
// "Geralt attacks for 25 damage!"
console.log(geralt.getHealth());
// 100

Assignment

The manager needs us to refactor the user logic to follow an object-oriented structure.

Create a Customer class: