[TS] 접근 제어자 access modifier

김다빈·2023년 9월 4일

타입스크립트

목록 보기
9/13
post-thumbnail

📌 접근 제어자

class PostA {
  constructor(id: number, title: string) {
    this.id = id; //ERROR
    this.title = title; //ERROR
  }

  getPost() {
    return (`postId: ${this.id}, postTitle: ${this.title}.`)
  }
}

let post: PostA = new PostA(1, 'title 1');

생성자를 이용해서 매개변수 2개를 가져올 때 가져오는 매개변수를 this.id와 this.title에 할당한다. 근데 둘 다 타입에러가 발생.

타입스크립트에서는 this로 접근하는 속성들을 위한 타입이 class의 body에 지정되어 있어야 한다!

class PostA {
  id: number = 0;
  title: string = '';
  constructor(id: number, title: string) {
    this.id = id;
    this.title = title;
  }
}

✅ 접근 제어자

종류접근 범위
public디폴트 값이며, 어디서나 접근 가능
protected클래스 내, 상속받은 자식 클래스에서 접근 가능
private클래스 내에서만 접근 가능

아래처럼 사용할 수 있다.

class PostA {
  public id: number = 0; //public은 생략 가능. id는 PostA 클래스, 그 자식 클래스, 클래스 외부에서 모두 접근 가능한 속성이 된다.
  private title: string = ''; //title은 PostA 클래스 내에서만 접근 가능한 속성이 된다.
  constructor(id: number, title: string) {
    this.id = id;
    this.title = title;
  }
}
class PostA {
  private id: number = 0;
  protected title: string = '';
  constructor(id: number, title: string) {
    this.id = id;
    this.title = title;
  }

  getPost() {
    return (`postId: ${this.id}, postTitle: ${this.title}.`)
  }
}

class PostB extends PostA {
  getPost() {
    return (`postId: ${this.id}, postTitle: ${this.title}.`)
    //Type ERROR! id에 접근 불가
  }
}

let post: PostA = new PostA(1, 'title 1');
console.log(post.id)
//Type ERROR! id에 접근 불가
console.log(post.title)
//Type ERROR! title에 접근 불가

✅ 속성 정리하기

속성 정리 전

class PostA {
  public id: number = 0;
  private title: string = '';
  constructor(id: number, title: string) {
    this.id = id;
    this.title = title;
  }
}

속성 정리 후

class PostA {
  constructor(
    public id: number = 0,
    private title: string = ''
  )
}

생성자 작성 시 매개변수에 접근 제어자를 추가해서 작성할 수 있다. 기본값을 작성해서 초기화시켜줄 수도 있다.

이때, public 생략 불가능 (기본값이긴 하지만 속성 정리해서 작성할 때는 생략 불가능)

profile
Hello, World

0개의 댓글