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.
We'll cover the following...
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 ClassWithConstructorclass ClassWithConstructor {// Property to store the identifierid: number;// Constructor function to initialize the class with an identifierconstructor(_id: number) {// Assigning the constructor argument to the class propertythis.id = _id;}}
-
We define a class named
ClassWithConstructoron lines 2–11 that has a single property namedidof typenumber. -
We then have a function definition for a function named
constructoron lines 7–10 with a single parameter named_idof typenumber. Within this constructor function, we are setting the value of the internalidproperty to the value of the_idparameter that was ...