abstract class AC {
name: string;
constructor(name: string) {
this.name = name;
}
}
이런 방식은 명확하지만 변수 선언과 할당이 중복되는 느낌이 있다.
abstract class AC {
constructor(public name: string) {}
}
이게 가능한 이유는?
이건 파라미터 프로퍼티(Parameter Properties)
라는 TypeScript의 기능 덕분이다.
public, private, readonly, protected 등의 접근 제어자를 생성자 매개변수 앞에 붙이면
TypeScript는 해당 매개변수를 자동으로 클래스의 멤버 변수로 선언하고 초기화한다.
위 코드는 다음 두 단계를 자동으로 수행하는 것과 같다:
name: string 멤버 변수 선언
this.name = name 초기화
class User {
constructor(
private id: number,
public name: string,
readonly role: string
) {}
getId() {
return this.id;
}
}
id: 외부에서 접근 불가 (private)
name: 외부에서 자유롭게 접근 가능 (public)
role: 외부에서 읽기만 가능 (readonly)
언제 쓰면 좋을까?