![[TypeScript] TypeScript 접근제한자(public, protected, private, readonly) [5/26 study]](https://img1.daumcdn.net/thumb/R750x0/?scode=mtistory2&fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdna%2FbhUQOQ%2FbtsH0lfZWxw%2FAAAAAAAAAAAAAAAAAAAAAHiKCuY4MlDlRgadH71xhIhMFP11SscPfcX0QE9cOcKb%2Fimg.png%3Fcredential%3DyqXZFxpELC7KVnFOS48ylbz2pIh7yKj8%26expires%3D1761922799%26allow_ip%3D%26allow_referer%3D%26signature%3DNl3ZqeWQXr065XzyzS9%252F9%252Fm41m0%253D)
TypeScript 접근제한자(public, protected, private, readonly)
타입스크립트에는 접근 제한자(Access modifier)인 public, protected, private를 지원하며, 이를 통해 외부에서 특정 메서드나 프로퍼티에 접근 범위를 지정할 수 있다.
❗️public
public은 어디에서나 접근할 수 있으며 생략 가능한 default 값이다.
class Greeter {
  public greet() {
    console.log("hi!");
  }
}
const g = new Greeter();
g.greet();
❗️protected
protected는 해당 클래스 혹은 서브클래스의 인스턴스에서만 접근이 가능하다.
class Greeter {
  public greet() {
    console.log("Hello, " + this.getName());
  }
  protected getName() {
    return "hi";
  }
}
 
class SpecialGreeter extends Greeter {
  public howdy() {
    // OK to access protected member here
    console.log("Howdy, " + this.getName());
  }
}
const g = new SpecialGreeter();
g.greet(); // OK
g.getName();
Property 'getName' is protected and only accessible within class 'Greeter' and its subclasses.단, 서브클래스에서 protected로 된 값을 public으로 오버라이딩한다면 해당 값은 public으로 취급된다.
오버라이딩할 경우, 상위클래스의 return 타입과 같아야 한다 그렇지 않으면 에러를 반환한다.
❗️private
private는 해당 클래스의 인스턴스에서만 접근 가능하다.
class Base {
  private x = 0;
}
const b = new Base();
// Can't access from outside the class
console.log(b.x);
Property 'x' is private and only accessible within class 'Base'.class Derived extends Base {
  showX() {
    // Can't access in subclasses
    console.log(this.x);
Property 'x' is private and only accessible within class 'Base'.
  }
}비공개 멤버는 파생 클래스에 표시되지 않으므로 파생 클래스에서 해당 멤버의 공개 범위를 늘릴 수 없습니다.
class Base {
  private x = 0;
}
class Derived extends Base {
Class 'Derived' incorrectly extends base class 'Base'.
  Property 'x' is private in type 'Base' but not in type 'Derived'.
  x = 1;
}서브클래스를 public으로 바꾸어주려고 하면 에러가 뜬다.
❗️readonly
필드 앞에 읽기 전용 수정자를 붙일 수 있습니다. 이렇게 하면 생성자 외부에서 필드에 할당할 수 없습니다.
class Greeter {
  readonly name: string = "world";
 
  constructor(otherName?: string) {
    if (otherName !== undefined) {
      this.name = otherName;
    }
  }
 
  err() {
    this.name = "not ok";
Cannot assign to 'name' because it is a read-only property.
  }
}
const g = new Greeter();
g.name = "also not ok";
Cannot assign to 'name' because it is a read-only property.
❗️참고
https://www.typescriptlang.org/docs/handbook/2/classes.html#readonly
Documentation - Classes
How classes work in TypeScript
www.typescriptlang.org
❗️마무리
class문법을 이제 막 배우고 있는데 접근 제한자 부분이 이해가 되면서 안되는 느낌이라서 찾아보고 포스팅 해보았다 도움이 되었으면 좋겠다 오늘도 화이팅🔥
프론트엔드 공부일지 입니다.
포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!
![[TypeScript] TypeScript 공부일지: 배열과 튜플 [5/27 study]](https://img1.daumcdn.net/thumb/R750x0/?scode=mtistory2&fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdna%2Fb4x68H%2FbtsHZ6QWxjH%2FAAAAAAAAAAAAAAAAAAAAABsvS7K8mZ9utOE5TSK1GL7cGDQ2xB1x2dMhPnUV3PDG%2Fimg.png%3Fcredential%3DyqXZFxpELC7KVnFOS48ylbz2pIh7yKj8%26expires%3D1761922799%26allow_ip%3D%26allow_referer%3D%26signature%3DC%252BpwwcHVt1vZj3eEM0IwYjZLht8%253D) 
                  ![[TypeScript] TypeScript 공부일지: 원시타입 [5/27 study]](https://img1.daumcdn.net/thumb/R750x0/?scode=mtistory2&fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdna%2FbpMuem%2FbtsHZ64tX6O%2FAAAAAAAAAAAAAAAAAAAAAC3NNCv0B0qjwRJG77lCSlwS32CQm6Siwlid91EkS6lF%2Fimg.png%3Fcredential%3DyqXZFxpELC7KVnFOS48ylbz2pIh7yKj8%26expires%3D1761922799%26allow_ip%3D%26allow_referer%3D%26signature%3DnK0UFV%252By5pXGXyWoWoovvH5VxBk%253D) 
                  ![[TypeScript] TypeScript의 동작 원리 [5/25 study]](https://img1.daumcdn.net/thumb/R750x0/?scode=mtistory2&fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdna%2Ftphmo%2FbtsHZZRWTYw%2FAAAAAAAAAAAAAAAAAAAAAFkBqEbDA1j_vupSsMI0xnPExZfgEs6LqN2DO-H9mVfD%2Fimg.png%3Fcredential%3DyqXZFxpELC7KVnFOS48ylbz2pIh7yKj8%26expires%3D1761922799%26allow_ip%3D%26allow_referer%3D%26signature%3DLyHBHWD0KP5nSf2Ch1mZnML%252F6vk%253D) 
                  ![[TypeScript] JavaScript만 사용하는 것과 비교해 TypeScript를 사용하는 이유 [5/25 study]](https://img1.daumcdn.net/thumb/R750x0/?scode=mtistory2&fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdna%2FcNqkoS%2FbtsH0po2XEd%2FAAAAAAAAAAAAAAAAAAAAABR1ANyhcNpjmBOeavpC1uR_RHDZLxa_BqcJMG5SfzQ8%2Fimg.png%3Fcredential%3DyqXZFxpELC7KVnFOS48ylbz2pIh7yKj8%26expires%3D1761922799%26allow_ip%3D%26allow_referer%3D%26signature%3DDl3bVXGRWSDtFc17C5agW1AQVIc%253D)