본문 바로가기
C.W.K.
Stream
Lesson 05 of 06 · published

매개변수 프로퍼티: 생성자 선언을 줄일 때의 기준

~7 min · classes, parameter-properties, shorthand

Level 0Curious
0 XP0/93 lessons0/23 achievements
0/100 XP to next level100 XP to go0% complete
"짧은 문법은 반복을 없애 주지만, 생성자가 하는 일을 감추면 오히려 비싸져."

선언과 대입을 한 번에

생성자 매개변수 앞에 public, private, protected, readonly 중 하나를 붙이면 그 매개변수가 곧 인스턴스 프로퍼티가 돼. constructor(public name: string, readonly id: number) {}는 필드 선언과 this.name = name 대입을 함께 줄인 표현이야.

제한자 없는 일반 매개변수는 프로퍼티가 되지 않아.

언제 읽기 좋아지는가

작은 값 객체나 의존성 주입처럼 '받은 값을 그대로 보관한다'가 생성자의 전부라면 매개변수 프로퍼티가 중복을 깔끔하게 줄여. 선언을 한 줄씩 따라가도 상태가 선명하고, 접근 범위도 같은 자리에서 보이지.

반대로 검증, 정규화, 기본값 계산이 많은 생성자에서는 짧은 문법이 실제 초기화 순서를 숨길 수 있어. constructor(public email: string)이라고 써 놓고 본문에서 별도 정규화 값을 관리하면 어느 값이 계약인지 흐려져. 그런 경우에는 필드와 대입을 명시하는 편이 낫다.

매개변수 프로퍼티는 '받아서 그대로 보관'하는 의도가 분명할 때 가장 좋아. 변환과 검증이 끼어들면 몇 줄을 아끼기보다 초기화 과정을 드러내.

Code

Parameter property vs 명시 형태·typescript
// Parameter property — 한 가지에 3개.
class User {
  constructor(
    public id: number,
    public name: string,
    private _email: string,
    readonly createdAt: Date = new Date(),
  ) {}

  get email(): string {
    return this._email;
  }
}

const u = new User(1, 'Pippa', 'a@b.c');
u.name;            // ✅ public
u.id;              // ✅ public
u.createdAt;       // ✅ readonly
u.email;           // ✅ getter 통해
// u._email;       // ❌ private
// u.createdAt = new Date();  // ❌ readonly

// 명시 동등 — 훨씬 김.
class UserExplicit {
  public id: number;
  public name: string;
  private _email: string;
  readonly createdAt: Date;

  constructor(id: number, name: string, _email: string, createdAt: Date = new Date()) {
    this.id = id;
    this.name = name;
    this._email = _email;
    this.createdAt = createdAt;
  }
}

External links

Exercise

기존 클래스를 매개변수 프로퍼티로 다시 써서 줄 수와 가독성을 비교해. 생성자에 검증을 추가한 뒤 단축 문법이 여전히 초기화 의도를 잘 보여 주는지도 판단해.
Hint
단순 대입은 매개변수 프로퍼티로 줄여. 검증이나 변환이 들어가는 값은 명시적인 필드와 대입으로 보여 줘.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.