Here’s a rewritten version of the article:
Unlocking the Power of Constructors in TypeScript
When working with classes in TypeScript, understanding constructors is crucial. A constructor is a special method that’s automatically called when you create a new instance of a class using the new
keyword. Its primary purpose is to initialize the properties of the new object.
Demystifying Constructors
To create a constructor, you use the constructor
keyword inside a class. The syntax is straightforward: ClassName { constructor(parameters) {... } }
. Here, ClassName
is the name of the class, constructor
is the keyword, and parameters
are the values used to initialize the class properties.
Key Takeaways
- The constructor method must always be named as
constructor
. - A class can have only one constructor.
Example 1: Initializing Properties with Constructors
Let’s create a Student
class with two properties: name
and gpa
. Our constructor method initializes these properties by assigning the values of its arguments to the respective class properties:
typescript
class Student {
constructor(name: string, gpa: number) {
this.name = name;
this.gpa = gpa;
}
}
Example 2: Creating Multiple Instances
Now, let’s rewrite the previous program to create two instances of the Student
class. We’ll also create a printInfo()
method to print the name
and gpa
properties of the objects:
class Student {
constructor(name: string, gpa: number) {
this.name = name;
this.gpa = gpa;
}
printInfo() {
console.log(<code>Name: ${this.name}, GPA: ${this.gpa}</code>);
}
}
const student1 = new Student("Leon Kennedy", 3.8);
const student2 = new Student("Ada Wong", 3.6);
student1.printInfo(); // Output: Name: Leon Kennedy, GPA: 3.8
student2.printInfo(); // Output: Name: Ada Wong, GPA: 3.6
<p><strong>Constructor Parameter Properties (Shorthand)</strong></p>
<p>You can also declare and initialize properties directly in the constructor parameters by adding visibility modifiers such as <code>public</code>, <code>private</code>, <code>protected</code>, or <code>readonly</code>. This reduces boilerplate code and makes your code more concise:</p>
<p><code>typescript
class Student {
constructor(public name: string, private gpa: number) {}
}
</code></p>
<p><strong>Default Values and Inheritance</strong></p>
<p>You can also provide default values for constructor parameters. If no arguments are passed, the default values are used. Additionally, when you derive one class from another, the derived class must call <code>super()</code> in its constructor to invoke the constructor of the base class:</p>
<p>“`typescript
class Person {
constructor(name: string) {
this.name = name;
}
}
class Student extends Person {
constructor(name: string, gpa: number = 4.0) {
super(name);
this.gpa = gpa;
}
}
“`
By mastering constructors in TypeScript, you’ll be able to create more robust and maintainable classes that simplify your development workflow.