BeCuriouzLearn something new every day
One Copy for the Class, One Line for the Constructor
💡 Use static for data shared by the whole class, and parameter properties to declare-and-assign instance fields in a single constructor line.
Recall from earlier cards that each new call creates its own instance with its own fields. But some data belongs to the class itself, not to any one object. A static member lives on the class and is shared by everyone. Mark it with the static keyword and access it through the class name — not through an instance.
class Circle {
static readonly PI = 3.14159;
static count = 0;
constructor(public radius: number) {
Circle.count++; // shared counter
}
area() {
return Circle.PI * this.radius ** 2;
}
}
new Circle(1);
new Circle(2);
console.log(Circle.count); // 2That constructor(public radius: number) is the second trick: a parameter property. Prefixing a constructor parameter with an access modifier (public, private, protected, or readonly) tells TypeScript to declare the field and assign it automatically. It collapses the usual three-step ritual — declare, accept, assign — into one line.
// Without the shorthand — the verbose form:
class Point {
private x: number;
private y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
}
// With parameter properties — identical behavior:
class Point2 {
constructor(private x: number, private y: number) {}
}Key rule: static members are reached via ClassName.member and are not visible on instances (new Circle(1).count is an error). Parameter properties only work in the constructor, and the modifier is what triggers the magic — a bare constructor(radius: number) is just a plain parameter, not a field.