TypeScript Class Constructors Tutorial
In this TypeScript tutorial we learn how to initialize an object with default values by using a special method called a constructor.
How to define a class constructor method
We can create a method that will allow us to populate properties at the same time as we create an object. It’s similar to instantiating an array.
A constructor method uses two special keywords.
- constructor
- this
First, we start by declaring the properties we want to be able to initialize with values.
class Person {
firstName
lastName
}
Next, we define the constructor method with the keyword constructor as the method name.
class Person {
firstName
lastName
constructor() {
}
}
Then, we add the parameters we want to initialize to the parameter list and assign them to our properties.
class Person {
firstName
lastName
constructor(fn: string, ln: string) {
this.firstName = fn
this.lastName = ln
}
}
We would expect that we could just assign the value of the method parameter to the property, but we can’t.
We need to prefix the property with the keyword this .
The this keyword represents the calling object. We can think of it this way, when we create an object, that object’s name will replace the this keyword.
How to construct an object
Now that we have our constructor method defined, we can use it to populate our properties with values when we create the object.
To this we add arguments for the parameters in the parentheses of the class name when we create the object.
class ClassName {
property
constructor(param: type) {
this.property = param
}
}
// construct object
// with values
let obj_name = new ClassName(param)
class Person {
firstName
lastName
constructor(fn: string, ln: string) {
this.firstName = fn
this.lastName = ln
}
}
let p1 = new Person("John", "Doe")
console.log(p1)
Summary: Points to remember
- To create a class constructor we define a method called constructor in the class with parameters for the properties we want to initialize with data.
- The properties that we want to initialize must be declared before we try to use them in the constructor.
- The this keyword refers to the calling object.