private property is only accessible within its class
two syntax
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// General syntax classAnimal{ private name: string; constructor(theName: string) { ... } } new Animal("Cat").name; // Error, cuz name is private in Animal
// Syntax that ECMAScript supports natively classAnimal{ #name: string; constructor(theName: string) { this.#name = theName; } } new Animal("Cat").#name; // Error, cuz #name is private in Animal
Protected
protected property is accessible within its class and its deriving classes
constructor can also be protected, which means that the class cannot be instantiated outside of its containing class, but can be extended
classEmployeeextendsPerson{ private department: string; constructor(name: string, department: string) { super(name); this.department = department; } // Notice that we can access the protected name here, in deriving class publicgetElevatorPitch() { return`Hello, my name is ${this.name} and I work in ${this.department}.`; } }
let tom = new Employee("Tom", "Sales"); console.log(tom.name); // Error, cuz name is protected in Person
let john = new Person("John"); // Error, cuz constructor of Person is protected
Readonly
readonly property must be initialized at their declaration or in the constructor
1 2 3 4 5 6 7 8 9
classPerson{ readonly school: string = "SCUT"; readonly name: string; constructor(theName: string) { this.name = theName; } } let maggie = new Person("Maggie"); maggie.name = "mag"; // Error, cuz name is readonly
Parameter property
we can use parameter properties to simplify the syntax, which lets us to create and initialize a member in one place
classAccountingDepartmentextendsDepartment{ constructor() { super("Accounting"); } printMeeting() { console.log("Meeting of accounting department is at 10am"); } generateReports() { console.log("Generating accounting reports..."); } }
let d: Department; // OK to create a reference to an abstract type d = new Department(); // Error to create instance of abstract class d = new AccountingDepartment(); // OK to create and assign a non-abstract subclass
d.printName(); // OK d.printMeeting(); // OK d.generateReports(); // Error, cuz generateReports does not exist on type Department
Using class as an interface
a class declaration creates two things:
a type representing instances of the class
a constructor function
As it creates types, so we could use class like interface.