클래스의 속성에 readonly
키워드를 사용하면 접근만 가능하다.
class Developer {
readonly name: string;
constructor(theName: string) {
this.name = theName;
}
}
let john = new Developer("John");
john.name = "John"; // error! name is readonly.
이처럼 readonly
를 사용하면 constructor()
함수에 초기값 설정 로직을 넣어줘야 하므로
다음과 같이 인자에 readonly
키워드를 추가해서 코드를 줄일 수 있다.
class Developer {
readonly name: string;
constructor(readonly name: string) {
}
}
타입스크립트는 객체의 특정 속성의 접근과 할당에 대해 제어할 수 있다.
이는 해당 객체가 클래스로 생성한 객체여야 한다.
class Developer {
name: string;
}
const josh = new Developer();
josh.name = 'Josh Bolton';
위 코드는 클래스로 생성한 객체의 name 속성에 Josd Bolton이라는 값을 대입한 코드이다.
이제 josh 객체의 name 속성은 Josh Bolton이라는 값을 가진다.
여기서 만약 name 속성에 제약 사항을 추가하고 싶다면 get
과 set
을 활용한다.
(get
만 선언하고 set
을 선언하지 않는 경우, 자동으로 readonly
로 인식)
class Developer {
private name: string;
get name(): string {
return this.name;
}
set name(newValue: string) {
if (newValue && newValue.length > 5) {
throw new Error('이름이 너무 길어요');
}
this.name = newValue;
}
}
const josh = new Developer();
josh.name = 'Josh Bolton'; // Error
josh.name = 'Josh';
추상 클래스는 인터페이스와 비슷한 역할을 하지만 조금 다른 특징을 가진다.
특정 클래스의 상속 대상이 되는 클래스이며, 좀 더 상위 레벨에서 속성, 메서드의 모양을 정의한다.
abstract class Developer {
abstract coding(): void; // 'abstract'가 붙으면 상속 받은 클래스에서 무조건 구현해야 함
drink(): void {
console.log('dring sth');
}
}
class FrontEndDeveloper extends Developer {
coding(): void {
// Developer 클래스를 상속받은 클래스에서 무조건 정의해야 하는 메서드
console.log('developer web');
}
design(): void {
console.log('design web');
}
}
const dev = new Developer(); // error: cannot create an instance of an abstract class
const josh = new FrontEndDeveloper();
josh.coding(); // develop web
josh.drink(); // dringk sth
josh.design(); // design web