Flexible constructors in typescript with optionals

When initializing objects in typescript we often do not want to or can provide all properties for the object. Depending on the use case we may want to provide different values in the constructor. There is a way to achieve this:

class Vehicle {
    color: string;
    seats: number;
    doors: number;
    amountOfTires: number = 4;
 
    constructor(data?: {
        color?: string,
        seats?: number,
        doors?: number,
        amountOfTires?: string
    }){
        if(data){
            this.color = data.color;
            this.seats = data.seats;
            this.doors = data.doors;
            // we do an extra check for the amount of tires, because it would override our default value 4 to undefined
            if(amountOfTires){
                this.amountOfTires = data.amountOfTires;
            }
        }
    }
}

By making “data” optional we can also provide an empty constructor when creating an object. Take a look at the usage examples:

let unknownVehicle: Vehicle = new Vehicle();
console.log(JSON.stringify(unknownVehicle));
// prints {"amountOfTires": 4}
 
let motorBike: Vehicle = new Vehicle({
    color: "blue",
    amountOfTires: 2,
    seats: 2
});
console.log(JSON.stringify(motorBike));
// prints {"color": "blue", "amountOfTires": 2, "seats": 2}
 
let car: Vehicle = new Vehicle({
    color: "red",
    seats: 5,
    doors: 5
});
console.log(JSON.stringify(car));
// prints {"color": "red", "amountOfTires": 4, "seats": 5, "doors": 5}