Search⌘ K
AI Features

Class Constructors and Modifiers

Explore how to define and use class constructors in TypeScript to initialize properties efficiently. Learn about public and private access modifiers to manage property accessibility and protect data within classes. This lesson helps you write better structured and safer TypeScript classes by controlling how class members are accessed and initialized.

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:

TypeScript 4.9.5
// 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 ...