![[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%3D1759244399%26allow_ip%3D%26allow_referer%3D%26signature%3DzaJlRf6NKC9RdzGqCPLBA%252Fyy8YE%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문법을 이제 막 배우고 있는데 접근 제한자 부분이 이해가 되면서 안되는 느낌이라서 찾아보고 포스팅 해보았다 도움이 되었으면 좋겠다 오늘도 화이팅🔥
프론트엔드 공부일지 입니다.
포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!