본문 바로가기
개발공부

#6. 클래스

by 반류연 2025. 2. 27.

※ 이 글은 이정환 강사님의 '한 입 크기로 잘라먹는 타입스크립트' 강의를 본 뒤 정리한 글입니다.

 

 

자바스크립트에서의 클래스

  • 동일한 모양의 객체를 더 쉽게 생성하도록 도와주는 문법
  • 기본구성: '필드'와 '생성자'
    • 필드: 해당 클래스가 생성할 객체가 갖는 프로퍼티
    • 생성자: 실질적으로 객체를 생성하는 함수
class Student{
  // 필드
  name;
  age;
  grade;
  
  // 생성자
  constructor(name, age, grade){
    this.name = name;
    this.age = age;
    this.grade = grade;
  }
}


// 클래스를 이용해 객체 생성하기
const studentA = new Student("홍길동","A",27);
const studentb = new Student("김철수","B",21);
  • 'new 클래스이름' 형태로 클래스의 생성자 함수를 호출, 매개변수로 전달한 값들을 각 this.프로퍼티 에 저장함.
    • this : 현재 만들고 있는 객체를 의미!
  • 생성자 함수 외에 일반 메서드 등록도 가능
class Student {
  // 필드
  name;
  grade;
  age;

  // 생성자
  constructor(name, grade, age) {
    this.name = name;
    this.grade = grade;
    this.age = age;
  }

  // 메서드
  study() {
    console.log("열심히 공부 함");
  }

  introduce() {
    console.log(`안녕하세요! ${this.name}`입니다.); // this를 이용해 객체 프로퍼티 값 활용
  }
}

let studentB = new Student("홍길동", "A+", 27);

studentB.study(); // 열심히 공부 함
studentB.introduce(); // 안녕하세요! 홍길동입니다.
  • 클래스 상속: extends 키워드 사용
class StudentDeveloper extends Student{
  favoritSkill;
  
  //상위 클래스의 생성자 함께 호출
  constructor(name, grade, age, favoritSkill){
    super(name, grade, age);
    this.favoritSkill = favoritSkill;
  }
  
  programming(){
    console.log(`${this.favoritSkill}로 프로그래밍 함`);
  }
}

 

 

타입스크립트에서의 클래스

  • JS 클래스와 기본적인건 동일. 
  • TS에서는 필드 선언 시 타입 주석으로 타입을 정의해줘야 함 => 안 그러면 any 타입으로 취급, 오류 발생.
  • 생성자에서 필드값을 초기화 하지 않을 경우엔 초기값도 함께 명시해야 함.
class Employee{
  // 필드
  name: string = "";
  age: number = 0;
  position?: string = ""; // 선택적 프로퍼티로 만들고 싶을 경우 '?' 붙이기
  
 
  // 생성자
  constructor(name: string, age: number, position: string){
    this.name = name;
    this.age = age;
    this.position = positon
  }
  
  
  // 메서드
  work(){
    console.log("일함");
  }
}

 

  • TS의 클래스는 타입으로 사용 가능 => 해당 클래스가 생성하는 객체의 타입과 동일한 타입이 됨.
class Employee {
  (...)
}

// Employee 클래스를 타입처럼 사용
const employeeC: Employee = { 
  name: "",
  age: 0,
  position: "",
  work() {},
};


// employeeC 변수는 name, age, position 프로퍼티와 work 메서드를 갖는 객체타입으로 정의됨

 

  • 상속의 경우, 파생 클래스에서 생성자를 정의했다면 반드시 생성자 최상단에 슈퍼 클래스의 생성자를 호출해야 함.
class ExecutiveOfficer extends Employee {
  officeNumber: number;
  
  constructor(
    name: string,
    age: number,
    position: string,
    officeNumber: number,
  ){
    super(name, age, position);
    this.officeNumber = officeNumber;
  }
}

 

 

접근 제어자(Access Modifier)

  • 클래스의 특정 필드나 메서드에 접근할 수 있는 범위를 설정하는 기능
  • TS에서만 존재

1. public

  • 모든 범위에서 접근 가능
  • 접근 제어자를 따로 설정하지 않으면 기본 설정으로 적용됨
class Employee {
  // 필드
  public name: string;
  public age: number;
  public position: string;

  ...
}

const employee = new Employee("이정환", 27, "devloper");

// 외부 접근 가능!
employee.name = "홍길동";
employee.age = 30;
employee.position = "디자이너";

2. private

  • 클래스 내부에서만 접근 가능
class Employee {
  // 필드
  private name: string; // private 접근 제어자 설정
  public age: number;
  public position: string;

  ...

  // 메서드
  work() {
    console.log(`${this.name}이 일함`); // 여기서는 접근 가능
  }
}

const employee = new Employee("이정환", 27, "devloper");

employee.name = "홍길동"; // 오류! 외부 접근 불가능
employee.age = 30;
employee.position = "디자이너";

3. proteced

  • 클래스 내부 또는 파생 클래스 내부에서만 접근 가능
  • public과 private의 중간 개념
class Employee {
  // 필드
  private name: string; // private 접근 제어자 설정
  protected age: number;
  public position: string;

  ...

  // 메서드
  work() {
    console.log(`${this.name}이 일함`); // name: private. 여기서는 접근 가능
  }
}

class ExecutiveOfficer extends Employee {
 // 메서드
  func() {
    this.name; // private. 오류! 
    this.age; // protected: 확장 클래스에서 접근 가능
  }
}

const employee = new Employee("이정환", 27, "devloper");

employee.name = "홍길동"; // private. 오류!
employee.age = 30; // protected: 외부에서 사용 불가. 오류!

 

 

※ 생성자 매개변수에 접근 제어자를 설정한 경우

  • 필드 뿐만 아니라 생성자 매개변수에도 접근 제어자를 설정할 수 있음
  • 그러나 이 경우, 자동으로 필드도 함께 선언되기 때문에 같은 이름으로 필드를 중복 선언할 수 없게 됨
  • 'this.필드 = 매개변수' 역시 자동으로 수행됨으로 생성자 내부에 선언하지 않아도 됨
class Employee {
  // 필드 영역 제거
  
  // 생성자
  constructor (
    private name: string,
    protect age: number,
    public position: string,
  ) {
    //제거 가능
    this.name = name;
    this.age = age;
    this.position = position;
  }
  
  
  // 메서드
  work(){
    console.log(`{this.name} 일하는 중`);
  }
}

 

 

=>코드가 한결 간결해지기 때문에 보통 TS에서 클래스를 사용할 때는 매게변수에 접근제어자를 설정하여 불필요한 코드들을 제거하는 편임.

 

인터페이스+클래스

  • TS에서 인터페이스는 클래스의 설계도 역할을 할 수 있음
  • 인터페이스를 이용해 클래스에 존재하는 필드와 메서드를 깔끔하게 정의할 수 있음
interface CharacterInterface {
  name: string;
  moveSpeed: number;
  move(): void;
}

class Character implements ChracterInterface {
  constructor(
    public name: string,
    public moveSpeed: number,
    private extra: string
  ){}
  
  move(): void {
    console.log(`${this.moveSpeed} 속도로 이동!`);
  }
}
  • 코드 해석: 위 인터페이스를 확장하여 정의한 클래스들은 모두 인터페이스 타입을 만족하도록 구현해야 함.
    => 정확도 UP

'개발공부' 카테고리의 다른 글

#8. 타입 조작하기  (0) 2025.03.05
#7. 제네릭  (0) 2025.02.28
#5. 인터페이스  (0) 2025.02.26
#4. 함수와 타입  (0) 2025.02.25
#3. 타입스크립트 이해하기  (0) 2025.02.20