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
ClassWithConstructor
on lines 2–11 that has a single property namedid
of typenumber
. -
We then have a function definition for a function named
constructor
on lines 7–10 with a single parameter named_id
of typenumber
. Within this constructor function, we are setting the value of the internalid
property to the value of the_id
parameter that was ...