Classes
Classes
Section titled βClassesβWhat it means
Section titled βWhat it meansβTypeScript extends JavaScriptβs class syntax with type annotations for properties, method parameters, and return types, plus access modifiers (public, private, protected) that are enforced at compile time. It also supports a shorthand β parameter properties β for declaring and assigning constructor parameters to instance properties in one step.
Examples
Section titled βExamplesβclass Animal { private name: string; protected age: number;
constructor(name: string, age: number) { this.name = name; this.age = age; }
speak(): string { return `${this.name} makes a sound`; }}
class Dog extends Animal { speak(): string { return `${this.name} barks`; // Error: `name` is private to Animal, not accessible here }}
// Parameter properties: shorthand for declaring + assigning in the constructorclass Point { constructor(public x: number, public y: number) {}}const p = new Point(3, 4); // p.x === 3, p.y === 4, no manual assignment neededCommon mistake
Section titled βCommon mistakeβMarking a property private and then trying to access it from a subclass β private means βonly this exact class,β while protected means βthis class and its subclasses.β Mixing them up causes a compile error the moment you extend the class.
class Animal { private name: string; // only Animal itself can access `name` constructor(name: string) { this.name = name; }}
class Dog extends Animal { bark() { return `${this.name} barks`; // Error: 'name' is private and only accessible within class 'Animal' }}
// Fix: use `protected` if subclasses need accessclass Animal { protected name: string; constructor(name: string) { this.name = name; }}Quick practice
Section titled βQuick practiceβ-
Whatβs the difference between
privateandprotected?Answer
privatemembers are accessible only within the declaring class;protectedmembers are also accessible in subclasses. -
What does
constructor(public x: number)do that a plainconstructor(x: number)doesnβt?Answer
It's a parameter property β TypeScript automatically declaresxas a public instance property and assigns the constructor argument to it, without a manualthis.x = x;line. -
Are TypeScriptβs
private/protectedmodifiers enforced at runtime in the compiled JavaScript?Answer
No β they're compile-time-only checks. Once compiled to JavaScript, the properties are accessible like any other (though TypeScript also supports native JS#privatefields, which *are* enforced at runtime).