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 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
ClassWithCtorMods
on lines 1–6 that has a singleconstructor
function. -
This
constructor
function has two parameters:- The first is named
id
and is of typenumber
. - The second is named
name
and is of typestring
.
- The first is named
Note: We have marked the
id
property aspublic
within the constructor function definition, and we have marked thename
property asprivate
. This shorthand automatically creates an internalid
property and aname
property on the class itself, which can be used as standard properties.
-
We then create an instance of this class on line 9 ...