abstract class Shape {
constructor(protected readonly name: string) {}
abstract area(): number;
describe() { return `${this.name}: ${this.area()}`; }
}
class Circle extends Shape {
#radius: number;
constructor(radius: number) { super("circle"); this.#radius = radius; }
area() { return Math.PI * this.#radius ** 2; }
}
Access modifiers control who can use a member. Abstract classes are base classes that cannot be created directly. TypeScript's private is checked only at compile time, while #private is enforced by JavaScript at runtime.
Access modifiers:
publicis the default. Anyone can use the member.protectedmembers are visible in the class and its subclasses.privatemembers are visible only in the class that declares them.readonlystops reassignment after the constructor runs.
You can write a modifier on a constructor parameter, as in protected readonly name. This declares the property and assigns it in one step. It is called a parameter property.
An abstract class cannot be created with new. It can hold shared code plus abstract members that subclasses must implement.
private vs #private:
- TypeScript's
privateis compile-time only. In the output JavaScript, it is a normal property. You can reach it with bracket notation or from plain JavaScript. #radiusis a JavaScript private field. The runtime enforces it, so code outside the class truly cannot reach it.
publicis the default,protectedallows subclasses,privateallows only the class, andreadonlystops reassignment.- Parameter properties declare and assign a property in the constructor signature.
- You cannot create an abstract class with
new, and subclasses must implement its abstract members. privateis checked only by TypeScript, while#privateis enforced at runtime.
Read more
- Classes (https://www.typescriptlang.org/docs/handbook/2/classes.html)typescriptlang.org