타입스크립트는 readonly
modifier를 통해서 클래스의 property를 immutable하게 해줌.
readonly
property에 값을 할당하는거는 아래의 상황에서만가능함.
property를 변하지 않게 하려면 readonly
키워드를 사용하면됨.
class Person {
readonly birthDate: Date;
constructor(birthDate: Date) {
this.birthDate = birthDate;
}
}
아래는 readonly
인 birthDate
property에 값을 재할당하려 했기에 에러가 나옴.
let person = new Person(new Date(1990, 12, 25));
person.birthDate = new Date(1991, 12, 25); // Compile error
access modifier
와 같이 readonly
property의 선언과 초기화도 생성자를 통해서 할 수 있음.
class Person {
constructor(readonly birthDate: Date) {
this.birthDate = birthDate;
}
}
readonly | const | |
---|---|---|
사용 하는 곳 | 클래스 property | 변수 |
초기화 하는 시점 | 사용할 클래스 안에서의 선언이나 생성자안에서 | 변수 선언할때 |
readonly
access modifier를 class property를 고정값으로 만들때 사용할 수 있음readonly
property는 사용할 클래스 안에서 선언할때 아니면 생성자안에서 초기화 해야함