Classes and access modifiers
JavaScript already has classes, and TypeScript improves them with types and access control. A class groups data and behavior: properties hold the state and methods manipulate it. With types, the compiler checks that every property is initialized, that methods receive the right things and that from outside only what you want to expose is used. Today we build classes from scratch, with properties, constructor, modifiers, inheritance and abstract classes.
Properties and modifiers
There are three access modifiers. public is the default: it can be used from anywhere. private restricts access to the class itself. protected extends it to subclasses. In addition, readonly prevents reassigning a property after the constructor. These modifiers are only checked at compile time; if you need real privacy at runtime, JavaScript offers fields with # (like #balance), which TypeScript also understands. With strict, every property must be initialized in its declaration or in the constructor.
class BankAccount {
readonly id: number;
private balance: number;
constructor(id: number, initialBalance: number = 0) {
this.id = id;
this.balance = initialBalance;
}
deposit(amount: number): void {
if (amount <= 0) {
throw new Error('Amount must be positive');
}
this.balance += amount;
}
getBalance(): number {
return this.balance;
}
}
const account = new BankAccount(1, 100);
account.deposit(50);
console.log(account.getBalance()); // 150
// account.balance = 1000; // error: Property 'balance' is private
// account.id = 2; // error: Cannot assign to 'id' because it is a read-only propertyConstructor shortcut
Repeating the name of each property three times (declare, receive and assign) is tedious. TypeScript offers a shorthand: if you put a modifier before a constructor parameter, that parameter becomes a property and is assigned automatically. The previous class shrinks a lot. It is a TypeScript-specific feature, which some type-stripping tools do not support, so if your setup rejects it, use the long form.
Inheritance and abstract classes
With extends a class inherits properties and methods from another; in the subclass constructor you must call super before using this. An abstract class is a template that cannot be instantiated: it defines abstract methods with no body that subclasses are obliged to implement. With implements, a class promises to satisfy an interface. Keep in mind that inheritance creates coupling; often it is better to compose small objects.
abstract class Shape {
constructor(protected readonly name: string) {}
abstract area(): number;
describe(): string {
return this.name + ' with area ' + this.area().toFixed(2);
}
}
class Circle extends Shape {
constructor(private radius: number) {
super('Circle');
}
area(): number {
return Math.PI * this.radius ** 2;
}
}
class Rectangle extends Shape {
constructor(private width: number, private height: number) {
super('Rectangle');
}
area(): number {
return this.width * this.height;
}
}
const shapes: Shape[] = [new Circle(1), new Rectangle(2, 3)];
for (const shape of shapes) {
console.log(shape.describe());
}
// new Shape('x'); // error: Cannot create an instance of an abstract classA modern pattern worth knowing is to prefer composition over inheritance. Instead of creating a deep hierarchy of classes, define small interfaces, such as Printable or Serializable, and make your classes implement them or receive objects that satisfy them. That way you change behavior without touching the structure. Also, in TypeScript typing is structural: an object is compatible with an interface if it has the right shape, even if it does not declare implements. This makes code flexible and easy to test with mock objects.
✎ Mes notes
Enregistré seulement dans ce navigateur. Connectez-vous pour le garder dans votre compte.0/5000 caractères