...

/

Class Constructors and Modifiers

Class Constructors and Modifiers

Learn about using class constructors to accept arguments and initialize class properties and using public, private, and protected access modifiers in TypeScript.

In this lesson, we will learn the intricacies of class constructors and modifiers in TypeScript, exploring each concept individually while highlighting their interrelatedness.

Class constructors

Class constructors can accept arguments during their initial construction. This allows us to combine the creation of a class and the setting of its parameters into a single line of code.

Consider the following class definition:

// Class definition for a ClassWithConstructor
class ClassWithConstructor {
// Property to store the identifier
id: number;
// Constructor function to initialize the class with an identifier
constructor(_id: number) {
// Assigning the constructor argument to the class property
this.id = _id;
}
}
Class with a constructor
  • We define a class named ClassWithConstructor on lines 2–11 that has a single property named id of type number.

  • We then have a function definition for a function named constructor on lines 7–10 with a single parameter named _id of type number. Within this constructor function, we are setting the value of the internal id property to the value of the _id parameter that was ...