Constructor access modifiers

TypeScript also introduces a shorthand version of the constructor function, allowing you to specify parameters with access modifiers directly in the constructor. Consider the following code:

class classWithAutomaticProperties { 
    constructor(public id: number, private name: string){ 
    } 
} 
 
let myAutoClass =  
    new classWithAutomaticProperties(1, "className"); 
console.log(`myAutoClass id: ${myAutoClass.id}`); 
console.log(`myAutoClass.name: ${myAutoClass.name}`); 

This code snippet defines a class named ClassWithAutomaticProperties. The constructor function uses two arguments—an id of type number, and a name of type string. Note, however, the access modifiers of public for id and private for name, defined directly in the constructor function. This shorthand automatically creates a public id property on the ClassWithAutomaticProperties class, as well as a private name property.

This shorthand syntax is only available within the constructor function.

We then create a variable named myAutoClass and assign a new instance of the ClassWithAutomaticProperties class to it. Once this class is instantiated, it automatically has two properties: an id property of type number, which is public, and a name property of type string, which is private. Compiling the previous code, however, will produce a TypeScript compile error:

Property 'name' is private and only accessible within class 'classWithAutomaticProperties'.  

This error is telling us that the automatic property name is declared as private, and it is therefore unavailable to code outside the class itself.

While this shorthand technique of creating automatic member variables is available, it can make the code more difficult to read. In the author's opinion, it is generally better to use the more verbose class definitions that do not use this shorthand technique. By not using this technique, and instead listing all of the properties at the top of the class, it becomes immediately visible to someone reading the code what variables this class uses, and whether they are public or private. Using the constructor's automatic property syntax hides these parameters somewhat, forcing developers to sometimes reread the code to understand it. Whichever syntax you choose, however, try to make it a coding standard, and use the same syntax throughout your code base.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.21.100.34