Bitpath

Lesson 1 · Unit 07

Classes

A recipe for objects that carry their own data and methods

13 exercisesabout 3 min

What you practise

  • class, constructor shorthand, public, private and readonly, getters, implements, a class is also a type

Try a question from this lesson

Pick one

A class is a recipe for objects, and new makes one from it. Each object gets its own count. What does this print?

TypeScript
class Counter {
  count = 0;
  add() {
    this.count += 1;
  }
}
const a = new Counter();
const b = new Counter();
a.add();
a.add();
console.log(a.count, b.count);

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Fields, constructor, methods

A class lists the data each object holds (its properties, called fields in a class) and what it can do (methods).

new Account("Ada") builds one object and runs the constructor to set it up. Inside the class, this means "the object this was called on". So acc.deposit(50) changes the balance of acc and of no other account.

TypeScript
class Account {
  owner: string;
  balance = 0;

  constructor(owner: string) {
    this.owner = owner;
  }
  deposit(amount: number) {
    this.balance += amount;
  }
}
const acc = new Account("Ada");
acc.deposit(50);
console.log(acc.owner, acc.balance);
// Ada 50

Concept

The constructor shorthand

Declaring a field, taking a parameter and copying one into the other is a lot of typing.

Write public, private or readonly in front of a constructor parameter, and the compiler does all three. public is the default: usable from anywhere. A readonly field is set in the constructor and never again.

TypeScript
class Account {
  constructor(
    public readonly owner: string,
    private balance: number,
  ) {}

  total(): number {
    return this.balance;
  }
}
const acc = new Account("Ada", 20);
console.log(acc.owner, acc.total());
// Ada 20

Concept

implements, and classes as types

implements is a promise to the compiler: this class has everything the interface lists. Break the promise and the class is rejected.

A class name is also a type. Square can annotate a variable the way number can. And a Square fits wherever a Shape is asked for, because it has what a Shape needs.

TypeScript
interface Shape {
  area(): number;
}
class Square implements Shape {
  constructor(private side: number) {}
  area(): number {
    return this.side * this.side;
  }
}
const s: Shape = new Square(3);
console.log(s.area()); // 9

9 more exercises in the app

  • 3× type the answer
  • 1× fill the blanks
  • 2× multiple choice
  • 1× true or false
  • 1× match the pairs
  • 1× order the lines

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy