티스토리 뷰

WEB/TypeScript

[TypeScript] 클래스

devOhzl 2024. 8. 18. 18:49

클래스

타입스크립트에서 클래스를 사용하게 되면 속성 부분의 타입을 constructor 위의 클래스 바디 부분에 타입 명시를 해줘야한다.

초기값이 필요하다면 type 선언 뒤에 할당 연산자를 통해 값을 입력하면 된다.

class UserA {
  first: string = ''
  last: string = ''
  age: number
  constructor(first: string, last: string, age: number){
    this.first = first
    this.last = last
    this.age = age
  }
  getAge() {
    return `${this.first} ${this.last} is ${this.age}`
  }
}

 

각각의 속성을 지정할 때는 앞에 접근 제어자를 붙여야 한다.

 

접근 제어자 (Access Modifiers)

1️⃣ public  : 어디서나 자유롭게 접근 가능, 클래스 바디에서 생략하여 사용 가능

class UserA {
  public first: string = ''
  public last: string = ''
  public age: number
  constructor(first: string, last: string, age: n umber){
    this.first = first
    this.last = last
    this.age = age
  }
  getAge() {
    return `${this.first} ${this.last} is ${this.age}`
  }
}

class UserB extends UserA {
  getAge() {
    return `${this.first} ${this.last} is ${this.age}`
  }
}

class UserC extends UserB {
  getAge() {
    return `${this.first} ${this.last} is ${this.age}`
  }
}

const neo = new UserA('Neo', 'Anderson', 100)
console.log(neo.first)    // Neo
console.log(neo.last)    // Anderson
console.log(neo.age)    // 100

UserB의 getAge 메서드는 UserA의 getAge 메서드를 덮어 씌우게 된다.

접근 제어자 public 을 사용하였기 때문에 UserB 클래스에서 UserA가 가지고 있는 this의 first, last,age의 속성에 접근할 수 있다. 

UserC로 한번 더 덮어씌워도 아무 문제 없다.

2️⃣ protected : 나와 파생된 후손 클래스 내에서 접근 가능

class UserA {
  public first: string = ''
  protected last: string = ''
  public age: number = 0
  constructor(first: string, last: string, age: n umber){
    this.first = first
    this.last = last
    this.age = age
  }
  getAge() {
    return `${this.first} ${this.last} is ${this.age}`
  }
}

class UserB extends UserA {
  getAge() {
    return `${this.first} ${this.last} is ${this.age}`
  }
}

class UserB extends UserA {
  getAge() {
    return `${this.first} ${this.last} is ${this.age}`
  }
}

const neo = new UserA('Neo', 'Anderson', 100)
console.log(neo.first)    // Neo
console.log(neo.last)    // error : 'last'속성은 보호된 속성이며 'UserA' 클래스 및 해당 하위 클래스 내에서만 사용 가능하다

자신을 포함한 클래스 안쪽에서 사용하는 것은 문제가 되지 않지만, 클래스 바깥쪽에서 내용을 사용하는 것은 허용하지 않는다.

 

3️⃣ private : 나의 클래스에만 접근 가능

class UserA {
  public first: string = ''
  protected last: string = ''
  private age: number = 0
  constructor(first: string, last: string, age: n umber){
    this.first = first
    this.last = last
    this.age = age
  }
  protected getAge() {
    return `${this.first} ${this.last} is ${this.age}`
  }
}

class UserB extends UserA {
  getAge() {
    return `${this.first} ${this.last} is ${this.age}`
    // error : 'age'속성은 private이며 'UserA' 클래스 내에서만 접근 가능하다.
  }
}


const neo = new UserA('Neo', 'Anderson', 100)
console.log(neo.first)   // Neo
console.log(neo.last)    // error : 'last'속성은 보호된 속성이며 'UserA' 클래스 및 해당 하위 클래스 내에서만 사용 가능하다
console.log(neo.age)    // error : 'age'속성은 private이며 'UserA' 클래스 내에서만 접근 가능하다.
neo.getAge()		// error: 'getAge' 속성은 보호된 속성이며 'UserA' 클래스 및 해당 하위 클래스 내에서만 사용 가능하다

 

추가적으로 매개변수와 속성의 이름이 반복된다. 이 코드는 가독성이 좋지 않으므로 정리할 수 있다.

접근 제어자 public은 클래스 바디 안에서만 생략이 가능하므로 매개변수에서 바로 사용할 때는 생략할 수 없다.

class UserA {
  constructor(
    public first: string = '',
    public last: string = '', 
    public age: number = 0
    ){
    	// ...
  	}
  protected getAge() {
    return `${this.first} ${this.last} is ${this.age}`
  }
}

👉 매개변수 이면서 this 키워드로 접근할 수 있는 속성이 됨

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함