SyntaxStudy
Sign Up
TypeScript Classes, Access Modifiers, and Parameter Properties
TypeScript Beginner 1 min read

Classes, Access Modifiers, and Parameter Properties

TypeScript extends JavaScript classes with access modifiers: public, protected, and private. Public members (the default) are accessible everywhere. Protected members are accessible within the class and its subclasses. Private members are accessible only within the declaring class. TypeScript also supports the ECMAScript private field syntax using a # prefix, which enforces privacy at runtime rather than just compile time. Parameter properties are a TypeScript shorthand that combines constructor parameter declaration and class property declaration into a single statement. By prefixing a constructor parameter with an access modifier (or readonly), TypeScript automatically creates a class property and assigns the constructor argument to it. This eliminates boilerplate and is idiomatic TypeScript. The readonly modifier on a class property prevents it from being reassigned after the constructor runs. This is useful for modelling immutable value objects. TypeScript also supports abstract classes, which cannot be instantiated directly but can define abstract methods that subclasses must implement, combining the benefits of interfaces and base classes.
Example
// Parameter properties shorthand
class Person {
    constructor(
        public readonly id: number,
        public name: string,
        protected email: string,
        private _passwordHash: string,
    ) {}

    greet(): string {
        return `Hi, I'm ${this.name}`;
    }
}

// Abstract base class
abstract class Shape {
    constructor(public readonly color: string) {}

    abstract area(): number;      // must be implemented
    abstract perimeter(): number; // must be implemented

    describe(): string {
        return `A ${this.color} shape with area ${this.area().toFixed(2)}`;
    }
}

class Circle extends Shape {
    constructor(color: string, public readonly radius: number) {
        super(color);
    }
    area():      number { return Math.PI * this.radius ** 2; }
    perimeter(): number { return 2 * Math.PI * this.radius;   }
}

class Rectangle extends Shape {
    constructor(
        color: string,
        public readonly width: number,
        public readonly height: number,
    ) { super(color); }
    area():      number { return this.width * this.height; }
    perimeter(): number { return 2 * (this.width + this.height); }
}

const c = new Circle("red", 5);
const r = new Rectangle("blue", 4, 6);
console.log(c.describe()); // A red shape with area 78.54
console.log(r.describe()); // A blue shape with area 24.00