C.W.K.
Stream
Lesson 05 of 06 · published

Parameter Property: Constructor 단축형

~7 min · classes, parameter-properties, shorthand

Level 0Curious
0 XP0/93 lessons0/23 achievements
0/100 XP to next level100 XP to go0% complete
"필드 선언, assign, access modifier 적용 — 다 parameter list 에서."

단축형

TypeScript 가 constructor parameter 에 특별 문법 지원: parameter 를 access modifier (`public`, `private`, `protected`, `readonly`) 로 prefix, TypeScript 가 그 이름의 class 필드 선언, parameter 에서 자동 assign, modifier 적용.

class User {
  constructor(public name: string, private _email: string) {}
  // 동등:
  // name: string;
  // private _email: string;
  // constructor(name: string, _email: string) {
  //   this.name = name;
  //   this._email = _email;
  // }
}

한 parameter 에 3가지: 필드 선언, modifier, assignment. 단축형이 type system 의 어떤 체크도 잃지 않고 class 정의 간결하게 유지.

Parameter property 가 빛날 때

Data-bag class — constructor 가 parameter 를 필드로 저장만 하는 — 극적으로 collapse. 5 필드와 각 assign 하는 constructor 가진 class 가 15줄 대신 6줄. 단축형이 dependency-injection 패턴 (Angular, NestJS) 에서 특히 흔함, 거기 constructor 가 주로 assignment.

단축형 스킵할 때

Constructor 가 parameter 로 다른 거 하면 — validation, 도출, side effect — 명시 형태 유지. 단축형이 직접 필드 assignment 만 작동; logic 필요해지면 어쨌든 명시적이어야.

Parameter property 가 흔한 case 에서 명시성을 간결성과 거래. Constructor 의 유일한 일이 parameter 를 필드에 assign 일 때 써. Constructor 가 다른 거 해야 하는 순간 명시 형태로 전환.

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

쓴 class 를 parameter property 써서 다시 써. Before/after 줄 수 비교. 그다음 constructor 에 validation logic 추가 — 단축형에 뭐 일어나?
Hint
Constructor 가 assign 전 validate 해야 하면 (예: 유효 않은 입력에 throw), validation 결과 의존하는 필드엔 단축형 못 써. 단축형이 trivial assignment 에 작동; logic 이 명시 형태 강제.

Progress

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

댓글 0

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

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