Skip to content

Classes

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.

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 constructor
class Point {
constructor(public x: number, public y: number) {}
}
const p = new Point(3, 4); // p.x === 3, p.y === 4, no manual assignment needed

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 access
class Animal {
protected name: string;
constructor(name: string) { this.name = name; }
}
  1. What’s the difference between private and protected?

    Answerprivate members are accessible only within the declaring class; protected members are also accessible in subclasses.
  2. What does constructor(public x: number) do that a plain constructor(x: number) doesn’t?

    AnswerIt's a parameter property β€” TypeScript automatically declares x as a public instance property and assigns the constructor argument to it, without a manual this.x = x; line.
  3. Are TypeScript’s private/protected modifiers enforced at runtime in the compiled JavaScript?

    AnswerNo β€” they're compile-time-only checks. Once compiled to JavaScript, the properties are accessible like any other (though TypeScript also supports native JS #private fields, which *are* enforced at runtime).