Trong TypeScript, một data modifier (còn được gọi là access modifier) là một từ khóa dùng để giới hạn truy cập vào các thuộc tính và phương thức của một class hoặc interface. TypeScript hỗ trợ ba data modifier sau:
Thuộc tính hoặc phương thức được khai báo là public có thể được truy cập từ bên trong và bên ngoài class hoặc interface.
class Employee { public empCode: number; empName: string; constructor(empCode: number, empName: string) { this.empCode = empCode; this.empName = empName; } } let emp = new Employee(123, "James"); emp.empCode = 100; emp.empName = "Pers"
Thuộc tính hoặc phương thức được khai báo là private chỉ có thể được truy cập từ bên trong class hoặc interface đó.
class Employee { private empCode: number; empName: string; constructor(empCode: number, empName: string) { this.empCode = empCode; this.empName = empName; } } let emp = new Employee(123, "James"); emp.empCode = 100; //Compiler Error: Property 'empCode' is private and only accessible within class 'Employee'. emp.empName = "Pers"
Thuộc tính hoặc phương thức được khai báo là protected có thể được truy cập từ bên trong class đó hoặc các class con của nó.
class Employee { public empName: string; protected empCode: number; constructor(name: string, code: number) { this.empName = name; this.empCode = code; } } class SalesEmployee extends Employee { private department: string; constructor(name: string, code: number, department: string){ super(name,code); this.department = department } } let emp = new SalesEmployee("John", 124, "Sales"); console.log(emp.empCode); // Compiler Error: Property 'empCode' is protected and only accessible within class 'Employee' and its subclasses.