- Mastering TypeScript 3
- Nathan Rozentals
- 344字
- 2021-07-02 12:42:52
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.
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.