...

/

Constructor Parameter Properties and Property Accessors

Constructor Parameter Properties and Property Accessors

Discover how TypeScript shorthand access modifiers simplify class property creation by applying them to constructor parameters.

Introduction to TypeScript shorthand access modifiers

TypeScript also introduces a shorthand version for access modifiers that can be applied to parameters in a constructor function.

As an example of this, consider the following code:

class ClassWithCtorMods {
// Constructor function with parameters, 'id' and 'name'
// Using shorthand access modifiers, 'public' for 'id' and 'private' for 'name'
constructor(public id: number, private name: string) {
}
}
// Create an instance of ClassWithCtorMods and assign it to the variable 'myClassMod'
let myClassMod = new ClassWithCtorMods(1, "test");
// Log the value of the 'id' property to the console
console.log(`myClassMod.id = ${myClassMod.id}`);
// Log the value of the 'name' property to the console
console.log(`myClassMod.name = ${myClassMod.name}`);
Creating an instance with shorthand modifiers
  • We define a class named ClassWithCtorMods on lines 1–6 that has a single constructor function.

  • This constructor function has two parameters:

    • The first is named id and is of type number.
    • The second is named name and is of type string.

Note: We have marked the id property as public within the constructor function definition, and we have marked the name property as private. This shorthand automatically creates an internal id property and a name property on the class itself, which can be used as standard properties.

  • We then create an instance of this class on line 9 ...