readonly 속성 제어자란?
TypeScript의 속성 제어자 중 하나로, 해당 속성이 읽기 전용임을 나타낸다. 즉, readonly로 선언된 속성은 객체가 생성된 후에는 값을 변경할 수 없도록 보장한다.
readonly의 예시
constructor(private readonly usersService: UsersService) {}
readonly는 usersService 속성 앞에 선언되어 있다. 즉, usersService는 생성자에 의해 초기화 된 후에 값을 변경할 수 없음을 보장한다. 또한, 해당 속성엔 접근할 수 있지만 값을 재할당할 수는 없다.
readonly 동작 예시
class Example {
readonly property: string;
constructor(value: string) {
this.property = value; // 생성자에서 초기화 가능
}
printProperty() {
console.log(this.property); // 읽기 가능
}
}
const example = new Example('Hello');
example.printProperty(); // 출력: Hello
readonly와 const의 차이점 - 1 (TypeScript)
readonly: 클래스나 인터페이스의 속성을 변경하지 못하게 함
즉, readonly로 초기화 이후 재할당으로 인한 객체의 속성의 불변성을 지킨다.
class User {
readonly id: number;
constructor(id: number) {
this.id = id; // 생성자에서 초기화 가능
}
changeId(newId: number) {
// this.id = newId; // 오류: readonly 속성은 변경 불가
}
}
const user = new User(1);
console.log(user.id); // 출력: 1
const: 변수의 참조 재할당을 막는다
const는 참조를 고정시키고 속성은 변경할 수 있다.
const user = { id: 1 };
// user = { id: 2 }; // 오류: const 변수는 참조를 변경할 수 없음
user.id = 2; // 가능: 객체의 속성은 변경 가능
console.log(user.id); // 출력: 2
readonly와 const의 차이점 - 2 (TypeScript vs. C++)
TypeScript의 readonly는 C++에서 const 멤버 변수 동작과 유사하다.
#include <iostream>
using namespace std;
class User {
public:
const int id; // const 멤버 변수 (TypeScript의 readonly와 유사)
// 생성자에서만 초기화 가능
User(int userId) : id(userId) {}
void changeId() {
// id = 42; // 오류: const 멤버 변수는 변경 불가
}
};
int main() {
User user(1);
cout << "User ID: " << user.id << endl; // 출력: User ID: 1
// user.id = 2; // 오류: const 멤버 변수는 변경 불가
return 0;
}
TypeScript의 const는 C++에서 const 변수와 const 참조 동작과 유사하다.
#include <iostream>
using namespace std;
int main() {
const int x = 10; // x는 const 변수
// x = 20; // 오류: const 변수는 재할당 불가
const int* ptr = &x; // const 참조 (포인터가 가리키는 값 변경 불가)
// *ptr = 30; // 오류: const 참조로 값 변경 불가
int y = 20;
ptr = &y; // 가능: const는 참조 자체를 고정하지 않음
cout << *ptr << endl; // 출력: 20
return 0;
}
'Nest.js' 카테고리의 다른 글
[NestJS] export 키워드에 대해서 (1) | 2025.01.20 |
---|---|
[NestJS] 데코레이터에 대해서 (2) | 2025.01.20 |
[NestJS] 파일 끝의 export {};의 의미 | Top-Level await (0) | 2025.01.14 |
[NestJS] @Injectable() 데코레이터에 대하여 | IoC (0) | 2025.01.13 |