TypeScript Constructors

Initializing objects with custom values

🔧 What are Constructors?

Constructors are special methods that automatically run when creating a new object. They initialize object properties with values, making it easy to set up objects with specific data right from the start.


// Constructor example
class Person {
    name: string;
    age: number;

    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }
}

const person = new Person("Alice", 30);
                                    

Output:

Person { name: "Alice", age: 30 }

Constructor Features

🎬

Auto-Execution

Runs automatically on object creation

constructor() {
    console.log("Created!");
}
📥

Parameters

Accept values during initialization

constructor(name: string) {
    this.name = name;
}
âš¡

Initialization

Set up initial property values

constructor() {
    this.count = 0;
    this.active = true;
}
🎯

Shorthand

Quick property declaration

constructor(
    public name: string
) {}

🔹 Basic Constructor

Create a constructor to initialize object properties:

class Car {
    brand: string;
    model: string;
    year: number;

    constructor(brand: string, model: string, year: number) {
        this.brand = brand;
        this.model = model;
        this.year = year;
    }

    getInfo() {
        return `${this.year} ${this.brand} ${this.model}`;
    }
}

const myCar = new Car("Toyota", "Camry", 2023);
console.log(myCar.getInfo());

Output:

2023 Toyota Camry

🔹 Constructor with Default Values

Provide default values for optional parameters:

class Product {
    name: string;
    price: number;
    inStock: boolean;

    constructor(name: string, price: number, inStock: boolean = true) {
        this.name = name;
        this.price = price;
        this.inStock = inStock;
    }

    display() {
        return `${this.name}: $${this.price} - ${this.inStock ? 'Available' : 'Out of Stock'}`;
    }
}

const product1 = new Product("Laptop", 999);
const product2 = new Product("Phone", 599, false);

console.log(product1.display());
console.log(product2.display());

Output:

Laptop: $999 - Available

Phone: $599 - Out of Stock

🔹 Parameter Properties Shorthand

TypeScript allows you to declare and initialize properties directly in the constructor:

// Traditional way
class User {
    name: string;
    email: string;

    constructor(name: string, email: string) {
        this.name = name;
        this.email = email;
    }
}

// Shorthand way (recommended)
class UserShort {
    constructor(
        public name: string,
        public email: string,
        private password: string
    ) {}

    getInfo() {
        return `${this.name} (${this.email})`;
    }
}

const user = new UserShort("Bob", "[email protected]", "secret123");
console.log(user.getInfo());

Output:

🔹 Constructor with Validation

Add logic to validate data during object creation:

class Employee {
    constructor(
        public name: string,
        public age: number,
        public salary: number
    ) {
        if (age < 18) {
            throw new Error("Employee must be at least 18 years old");
        }
        if (salary < 0) {
            throw new Error("Salary cannot be negative");
        }
    }

    getDetails() {
        return `${this.name}, Age: ${this.age}, Salary: $${this.salary}`;
    }
}

const emp = new Employee("Sarah", 25, 50000);
console.log(emp.getDetails());

// This would throw an error:
// const invalidEmp = new Employee("Tom", 16, 30000);

Output:

Sarah, Age: 25, Salary: $50000

🔹 Multiple Initialization Patterns

Use optional parameters for flexible object creation:

class Rectangle {
    constructor(
        public width: number,
        public height: number = width // Default to square
    ) {}

    getArea() {
        return this.width * this.height;
    }

    getPerimeter() {
        return 2 * (this.width + this.height);
    }
}

const square = new Rectangle(5);
const rect = new Rectangle(5, 10);

console.log(`Square area: ${square.getArea()}`);
console.log(`Rectangle area: ${rect.getArea()}`);

Output:

Square area: 25

Rectangle area: 50

🧠 Test Your Knowledge

When does a constructor method execute?