×

typescript · level 2 · unit 5 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A is a blueprint for making objects with methods.

An interface describes a shape. A class goes further: it builds objects and gives them methods. Inside class Dog { }, list each property with its type, then write a , which runs once each time a new object is made.

Make an object with new: new Dog("Rex") calls the constructor with "Rex". Each object made way is an of the class. Inside the class, this means the instance being used right now, so this.name is its own name.

Methods are functions inside the class, written without the word function. A property can also start with a value, like count: number = 0;.

class Dog {
  name: string;
  constructor(name: string) {
    this.name = name;
  }
  bark(): string {
    return `${this.name} says woof!`;
  }
}
console.log(new Dog("Rex").bark(), new Dog("Bo").bark());

Class names start with a capital, like interfaces.