개발 공부/Typescript

Parameter Properties

차정 2025. 7. 5. 18:41

생성자 파라미터에 접근제어자 붙여 클래스 속성 선언과 초기화를 한번에 할 수 있는 타입스크립트의 문법적 설탕.


class Point {
  constructor(public x: number, public y: number) {
    // 여기서 this.x = x; this.y = y; 를 안 써도 자동 처리
  }
}

const p = new Point(10, 20);
console.log(p.x); // 10
console.log(p.y); // 20
  • 생성자 파라미터에 public/private/protected를 붙이면 자동으로 클래스 속성이 만들어지고 this에 할당된다.
  • JavaScript가 아니라 TypeScript 컴파일러가 해주는 문법적 설탕(syntax sugar)

 

아래와 사실상 동일

class Point {
  public x: number;
  public y: number;
  constructor(x: number, y: number) {
    this.x = x;
    this.y = y;
  }
}