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!
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:
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.
Let's create our first Car
object using the new
keyword:
