Readonly

Trong TypeScript, từ khóa "readonly" được sử dụng để chỉ định rằng một thuộc tính của một đối tượng (class, type, interface) chỉ có thể đọc và không thể ghi. Khi một thuộc tính được khai báo là "readonly", nó chỉ có thể được gán giá trị trong hàm khởi tạo hoặc bên ngoài định nghĩa của đối tượng đó.

class Employee { readonly empCode: number; empName: string; constructor(code: number, name: string) { this.empCode = code; this.empName = name; } } let emp = new Employee(10, "John"); emp.empCode = 20; //Compiler Error: Cannot assign to 'empCode' because it is a read-only property. emp.empName = 'Bill';
interface IEmployee { readonly empCode: number; empName: string } let empObj: IEmployee = { empCode: 1, empName: "John" } empObj.empCode = 2; // Compiler Error: Cannot assign to 'empCode' because it is a read-only property.
interface IEmployee { empCode: number; empName: string } let emp1: Readonly<IEmployee> = { empCode: 1, empName: 'John' } emp1.empCode = 2; // Compiler Error: Cannot assign to 'empCode' because it is a read-only property. emp1.empName = 'James'; // Compiler Error: Cannot assign to 'empName' because it is a read-only property.

Static

Trong TypeScript, từ khóa "static" được sử dụng để khai báo một thành viên của một lớp (class) là một thành viên tĩnh, nghĩa là nó thuộc về lớp chứ không phải một phiên bản (instance) cụ thể của lớp đó. Thành viên tĩnh có thể được truy cập trực tiếp thông qua lớp mà không cần tạo một phiên bản của lớp đó.

class MyClass { static staticProperty: string = "Hello, World!"; static staticMethod(): void { console.log("This is a static method."); } } console.log(MyClass.staticProperty); // Output: "Hello, World!" MyClass.staticMethod(); // Output: "This is a static method."

Trong ví dụ trên, chúng ta khai báo một lớp MyClass với một thành viên tĩnh staticProperty và một phương thức tĩnh staticMethod(). Chúng ta có thể truy cập vào thành viên tĩnh thông qua lớp MyClass mà không cần tạo một phiên bản của lớp đó.


Tài liệu tham khảo: