Lesson 3
Exploring Constructors in TypeScript Classes
Understanding Constructors in TypeScript

Welcome to the OOP station! Today, we're going to dive into constructors in TypeScript classes. Constructors play an essential role in creating and initializing objects. Picture a constructor as a blueprint — it details the components necessary for creating each object.

Just like JavaScript, if you don't provide a constructor in your TypeScript class, a default one will be supplied. Imagine this scenario as being given a blank blueprint sheet ready for you to customize!

Constructors in TypeScript

In TypeScript, constructors are defined using the keyword constructor within a class. These constructors can have parameters that initialize the properties of class instances. Think of this as specifying the components needed for a blueprint and their respective quantities. Let's exemplify this:

TypeScript
1class Car { 2 brand: string; 3 model: string; 4 color: string; 5 6 constructor(brand: string, model: string, color: string) { 7 this.brand = brand; 8 this.model = model; 9 this.color = color; 10 console.log(`Instantiated a Car instance with brand=${brand}, model=${model}, color=${color}`); 11 } 12}

Note that in TypeScript, we have to declare the types of the class properties before assigning them in the constructor. Each time we create a new Car object, we need these attributes to be supplied. You'll learn more about attributes in upcoming lessons.

Creating Objects Using Constructors

Let's create our first Car object using the new keyword:

TypeScript
1let myCar = new Car("Toyota", "Corolla", "red"); 2// Prints a message from the constructor: 3// Instantiated a Car instance with brand=Toyota, model=Corolla, color=red

myCar is a Car object, representing a red Toyota Corolla. This object has properties defined by the constructor!

Special Properties of Constructors

Although a TypeScript class can host numerous methods, it is bound by one condition — it can only accommodate a single constructor. If we attempt to declare more than one constructor, TypeScript will raise a SyntaxError.

In instances where no explicit constructor is defined, TypeScript provides a default one: constructor() {}.

Furthermore, we can assign default values to parameters as shown below:

TypeScript
1class Car { 2 brand: string; 3 model: string; 4 color: string; 5 6 // 'color' has a default value of "white" 7 constructor(brand: string, model: string, color: string = "white") { 8 this.brand = brand; 9 this.model = model; 10 this.color = color; 11 } 12}
Lesson Summary and Practice

Fantastic! You've now learned about TypeScript constructors, how to use them, their unique properties, and how they facilitate object creation when defining classes. Remember, practice is the key to mastery. Delve further into constructors and explore their potential. Happy coding!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.