Lesson 9
25 min
Typed properties, access modifiers, inheritance and implements.
Definition
A class is a blueprint that describes the data (properties) and the actions (methods) of a kind of object. An object built from this blueprint is called aninstance. The idea is to group, in the same place, the data and the code that works on it.
So far, you have described the shape of objects with interfaces. Classes go further: they describe the shape and also provide the code to build objects and act on them. They are widely used in structured applications, for example to represent a bank account, a user or a shopping cart.
A class is a template for creating objects that share the same structure and behavior. In TypeScript, you declare the properties with their type at the top of the class, then initialize them in the constructor.
class User {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
introduce(): string {
return "My name is " + this.name + " and I am " + this.age + " years old.";
}
}
const lea = new User("Lea", 25);
console.log(lea.introduce());
The constructor is a special method called automatically by new. The this keyword refers to the instance being created: this.name is the name property of that particular object. Each call to new User(...) creates an independent object, with its own values.
TypeScript checks that each declared property actually receives a value in the constructor. If you forget one, in strict mode, the editor reports an error: it is a protection against half-built objects.
TypeScript lets you control who can access the members of a class:
class BankAccount {
readonly accountNumber: string;
private balance: number = 0;
constructor(accountNumber: string) {
this.accountNumber = accountNumber;
}
deposit(amount: number): void {
if (amount > 0) {
this.balance += amount;
}
}
getBalance(): number {
return this.balance;
}
}
const account = new BankAccount("FR123");
account.deposit(100);
console.log(account.getBalance()); // 100
account.balance = 1000000; // Error: balance is private
account.accountNumber = "other"; // Error: accountNumber is read-onlyThis example illustrates the main benefit of private: the balance can only be changed by the class's methods, which check that the deposited amount is positive. No one outside can bypass this rule by writing directly to the property. This principle is called encapsulation.
Good to know
private is a TypeScript check, and it disappears at compilation. For real privacy at runtime, JavaScript offers the#property syntax.
Writing out the properties and then assigning them one by one is repetitive. TypeScript offers a shortcut: by adding a modifier in front of a constructor parameter, the property is created and initialized automatically.
class Product {
constructor(
public name: string,
public price: number,
private stock: number = 0,
) {}
isAvailable(): boolean {
return this.stock > 0;
}
}
const book = new Product("TS Guide", 29.9, 5);
console.log(book.name, book.isAvailable());The constructor body is empty ({} with no statements) because the modifiers do all the work. This is the notation you will meet most often in real projects, for example in web frameworks.
A getter (get) lets you read a computed value as if it were a simple property, and a setter (set) lets you control writing. They are used to expose a piece of data while keeping control over its validity.
class Temperature {
private celsius: number = 0;
get fahrenheit(): number {
return this.celsius * 1.8 + 32;
}
set value(c: number) {
if (c < -273.15) {
throw new Error("Impossible temperature");
}
this.celsius = c;
}
}
const t = new Temperature();
t.value = 20;
console.log(t.fahrenheit); // 68Accessors behave like properties: you write t.fahrenheitwithout parentheses. Writing the value, however, goes through the setter, which can reject an absurd value before it is stored.
A member declared static belongs to the class itself and not to its instances: you call it directly on the class name, without new. This is handy for constants or utility functions tied to the class.
class MathUtils {
static readonly PI = 3.14159;
static square(n: number): number {
return n * n;
}
}
console.log(MathUtils.PI); // 3.14159
console.log(MathUtils.square(4)); // 16A class can extend another with extends to take over its properties and methods. The super keyword calls the constructor of the parent class.
class Animal {
constructor(public name: string) {}
speak(): string {
return this.name + " makes a noise.";
}
}
class Dog extends Animal {
speak(): string {
return this.name + " barks!";
}
}
const rex = new Dog("Rex");
console.log(rex.speak()); // Rex barks!Here, Dog has no constructor: it uses the one from Animal. If the child class adds its own properties, you must write a constructor and call super(...) first, before using this. The speak method of the child class overrides the one from the parent class.
class Bird extends Animal {
constructor(name: string, public wingspan: number) {
super(name); // required before using this
}
}An abstract class, declared with abstract, serves only as a base for other classes: you can't create an instance of it directly. It can require its child classes to write certain methods.
abstract class Shape {
abstract area(): number;
describe(): string {
return "Area: " + this.area();
}
}
class Disc extends Shape {
constructor(private radius: number) {
super();
}
area(): number {
return Math.PI * this.radius * this.radius;
}
}
// const s = new Shape(); // Error: abstract classAn abstract class is therefore a partial contract: it requires the area method from all its children, while offering the describe method for free, which relies on it.
A class can commit to respecting an interface with implements. TypeScript then checks that it provides everything the interface requires.
interface Printable {
print(): string;
}
class Article implements Printable {
constructor(public title: string) {}
print(): string {
return "Article: " + this.title;
}
}
A class can implement several interfaces by separating them with commas, whereas it can only extend a single class. The interface describes what the class can do, without saying how: the class provides the code.
User(...) without new causes an error, because a class is not called like a function.super(...) must be called before any access to this.public, private, protected and readonly control access to members.extends lets you inherit from a class, implements lets you respect an interface.Exercise
Rectangle class with a width and a height (using the constructor shortcut) and an area() method. Then create a Square class that inherits from it.Going further
Cart class with a private property holding an array of items, a method to add an item and a method that returns the total.