Constructor Parameter Properties and Property Accessors
Discover how TypeScript shorthand access modifiers simplify class property creation by applying them to constructor parameters.
We'll cover the following...
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 consoleconsole.log(`myClassMod.id = ${myClassMod.id}`);// Log the value of the 'name' property to the consoleconsole.log(`myClassMod.name = ${myClassMod.name}`);
-
We define a class named
ClassWithCtorModson lines 1–6 that has a singleconstructorfunction. -
This
constructorfunction has two parameters:- The first is named
idand is of typenumber. - The second is named
nameand is of typestring.
- The first is named
Note: We have marked the
idproperty aspublicwithin the constructor function definition, and we have marked thenameproperty asprivate. This shorthand automatically creates an internalidproperty and anameproperty on the class itself, which can be used as standard properties.
-
We then create an instance of this class on line 9 ...