[한입챌린지]타입스크립트 DAY9

Lina Hongbi Ko·2025년 3월 13일
0
post-thumbnail

DAY9

2025년 3월 5일

✨ 자바스크립트의 클래스 소개

  • 동일한 객체를 만들때 클래스 사용 -> 객체를 만들어 내는 틀

  • 객체: 붕어빵 / 클래스: 붕어빵 기계

    /**
     * 클래스
     */
    
    let studentA = {
      name: '이정환',
      grade: 'A+',
      age: 27,
      study() {
        console.log('열심히 공부 함');
      },
      introduce() {
        console.log('안녕하세요!');
      },
    };
    
    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} 입니다!`);
      }
    }
    
    // 클래스를 이용해서 만든 객체 -> 인스턴스
    // 스튜던스 인스턴스
    let studentB = new Student('이정환', 'A+', 27);
    console.log(studentB); // Student { name: '이정환', grade: 'A+', age: 27 }
    studentB.study(); // 열심히 공부 함
    studentB.introduce(); // 안녕하세요! 이정환 입니다!
    
  • 클래스 확장 (상속)

    class StudentDeveloper extends Student {
      // 필드
      favoriteSkill;
    
      // 생성자
      constructor(name, grade, age, favoriteSkill) {
        super(name, grade, age);
        this.favoriteSkill = favoriteSkill;
      }
    
      // 메서드
      programming() {
        console.log(`${this.favoriteSkill}로 프로그래밍 함`);
      }
    }
    
    const studentDeveloper = new StudentDeveloper('이정환', 'B+', 27, 'TypeScript');
    console.log(studentDeveloper);
    // StudentDeveloper {name: '이정환', grade: 'B+', age: 27, favoriteSkill: 'TypeScript'}
    studentDeveloper.programming(); // TypeScript로 프로그래밍 함

✨ 타입스크립트의 클래스

  • 클래스 자체가 하나의 타입으로 작용함

    • 타입스크립트는 구조적으로 타입을 결정하는 구조적 타입 시스템을 따르기 때문
  • 타입스크립트 클래스의 상속

    • super()을 사용하지 않으면 오류 발생
    const employee = {
      name: '이정환',
      age: 27,
      position: 'developer',
      work() {
        console.log('일함');
      },
    };
    
    class Employee {
      // 필드
      name: string;
      age: number;
      position: string;
    
      // 생성자
      constructor(name: string, age: number, position: string) {
        this.name = name;
        this.age = age;
        this.position = position;
      }
    
      // 메서드
      work() {
        console.log('일함');
      }
    }
    
     // 클래스 상속
    class ExecutiveOfficer extends Employee{
      // 필드
      officeNumber: number;
    
      // 생성자
      constructor(name: string, age: number, position: string, officeNumber: number) {
        super(name, age, position);
        this.officeNumber = officeNumber;
      }
    }
    
    const employeeB = new Employee('이정환', 27, '개발자');
    console.log(employeeB); // Employee { name: '이정환', age: 27, position: '개발자' }
    
    const employeeC: Employee = {
      name: '',
      age: 0,
      position: '',
      work () {}
    }
    

✨ 접근 제어자

  • class modifier

  • 클래스를 만들 때, 특정 필드나 메서드에 접근할 수 있는 범위를 설정할 수 있는 문법

    • public, private, protected
  • public

    • 기본적인 접근 제어자
    • 자유롭게 인스턴스의 프로퍼티에 접근 가능하도록 함
  • private

    • 클래스 외부에서 프로퍼티에 접근하는게 제한됨 (내부에서만 접근 가능)
    • 만약, 접근하고 싶다면 클래스 내부의 메서드 안에서만 접근할 수 있음
      e.g) work() {console.log(${this.name} 일함)}
    • 파생 클래스에서도 접근할 수 없음
  • protected

    • 파생 클래스에서는 접근할 수 있게 함
    • 외부에서는 접근할 수 없지만, 파생 클래스 메서드 안에서는 접근할 수 있음
    class Employee {
      // 필드
      private name: string;
      protected age: number;
      public position: string;
    
      // 생성자
      constructor(name: string, age: number, position: string) {
        this.name = name;
        this.age = age;
        this.position = position;
      }
    
      // 메서드
      work() {
        console.log('일함');
      }
    }
    
    class ExecutiveOfficer extends Employee {
      // 필드
      officeNumber: number;
    
      // 생성자
      constructor(
        name: string,
        age: number,
        position: string,
        officeNumber: number
      ) {
        super(name, age, position);
        this.officeNumber = officeNumber;
      }
    
      // 메서드
      func() {
        this.name; // 오류 발생. name은 private 접근 제어자로 관리하므로 Employee 내부 클래스에서만 접근할 수 있고, 파생 클래스에서 접근할 수 없음
        this.age;
      }
    }
    
    const employee = new Employee('이정환', 27, 'developer');
    employee.name = '홍길동'; // 오류. 외부에서 접근 불가 (파생 클래스, 외부 모두 접근 불가능)
    employee.age = 30; // 오류. 외부에서 접근 불가 (파생 클래스에서만 가능)
    employee.position = '디자이너';
    
  • 생성자에 접근제어자를 설정하면 필드를 생략 해줘야함 -> 중복 오류 발생

    • 필드도 자동으로 생성하지만, 초기화도 자동으로 생성해줘서 초기화 설정도 생략해도 됨
    class Employee {
    
      // 생성자
      constructor(private name: string, protected age: number, public position: string) {}
    
      // 메서드
      work() {
        console.log('일함');
      }
    }

✨ 인터페이스와 클래스

  • 인터페이스가 정의하는 타입 객체를 클래스 객체가 생성하도록 정의할 수 있음

    • implements 사용 (구현한다)
    • 인터페이스는 클래스 객체의 설계도 역할을 함
  • 클래스 객체가 인터페이스 타입 객체를 구현하는 것임

    • 인터페이스는 마치 클래스의 설계도 역할을 한다고 생각하면 됨
  • 인터페스로 정의하는 필드들은 무조건 public임!!!

    • 인터페이스는 무조건 public 필드만 정의할 수 있음
    • 만약 다른 접근제어자를 쓰고 싶다면, 인터페이스가 아닌 곳에서 정의해줘야함 (e.g) constructor 매개변수)
  • 보통 클래스를 만들 때, 인터페이스로 설계도를 먼저 만들고 구현하는 것은 보통은 없음

    • 보통 라이브러리의 구현이나 굉장히 복잡하고 정교한 프로그래밍을 해야할 때 사용
    interface CharacterInterface {
      name: string;
      moveSpeed: number;
      move(): void;
    }
    
    class Character implements CharacterInterface {
      constructor(
        public name: string,
        public moveSpeed: number,
        private extra: string
      ) {}
    
      move(): void {
        console.log(`${this.moveSpeed} 속도로 이동!`);
      }
    }
    

출처: 한 입 크기로 잘라먹는 타입스크립트

profile
프론트엔드개발자가 되고 싶어서 열심히 땅굴 파는 자

0개의 댓글