Readonly<T>
Readonly<T> là utility type biến tất cả các property của object type T thành read-only.
Type argument của Readonly<T>
T
Type argument T nhận object type.
Ví dụ sử dụng Readonly
tstypePerson = {surname : string;middleName ?: string;givenName : string;};typeReadonlyPerson =Readonly <Person >;
tstypePerson = {surname : string;middleName ?: string;givenName : string;};typeReadonlyPerson =Readonly <Person >;
ReadonlyPerson ở trên sẽ giống với kiểu sau:
tstypeReadonlyPerson = {readonlysurname : string;readonlymiddleName ?: string;readonlygivenName : string;};
tstypeReadonlyPerson = {readonlysurname : string;readonlymiddleName ?: string;readonlygivenName : string;};
Tác dụng của Readonly không đệ quy
Readonly<T> chỉ biến các property trực tiếp của object type T thành read-only. Lưu ý rằng nếu property là một object, các property mà nó chứa sẽ không trở thành read-only.
Implementation của Readonly
Readonly<T> được implement như sau:
tstypeReadonly <T > = {readonly [P in keyofT ]:T [P ];};
tstypeReadonly <T > = {readonly [P in keyofT ]:T [P ];};
Thông tin liên quan
📄️ Readonly property của object type
Trong TypeScript, có thể đặt property của object thành read-only. Thêm modifier readonly vào property muốn đặt thành read-only. Khi cố gán giá trị cho property read-only, TypeScript compiler sẽ cảnh báo không thể gán.
📄️ Readonly modifier trong class
Trong TypeScript, thêm readonly modifier cho field để biến field đó thành chỉ đọc.
📄️ Readonly modifier của interface
Trong interface của TypeScript, có thể định nghĩa field chỉ đọc bằng cách thêm readonly modifier cho field.
📄️ Sự khác biệt giữa readonly và const
Trong JavaScript, biến khai báo bằng const không thể gán lại. Trong TypeScript, khi thêm modifier readonly vào property của object type, property đó không thể gán lại. Hai tính năng này giống nhau ở điểm "không thể gán lại". Vậy sự khác biệt là gì?