클래스 (Class)

Changhan·2025년 2월 3일

Typescript

목록 보기
24/29

타입스크립트에서 클래스를 정의하는 방법에 대해 알아보자.

클래스 정의하기

class Game {
  name: string;
  country: string;
  download: number;

  constructor(name: string, coutnry: string, download: number) {
    this.name = name;
    this.country = coutnry;
    this.download = download;
  }
  
  introduce() {
    return `${this.name}${this.country}에서 제작된 ${this.download}개의 다운로드를 달성한 게임이다`;
  }
}

const ow = new Game('Overwatch', 'US', 10000000);

Readonly 프로퍼티

class Singer {
  readonly name: string;
  age: number;

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }
}
const taeyeon = new Singer('태연', 32);
taeyeon.age = 23; 
taeyeon.name = '윤아'; // 값 변경 불가능!

readonly 키워드로 선언한 프로퍼티는 값 변경이 불가능하고, 값을 불러올 수만 있다. 이것은 자바스크립트로 실행될 때는 의미없는 코드지만 코드를 작성할 때 변경하는 것을 강제로 막아준다.

interface

클래스와 interface를 어떻게 조합할 수 있는지 알아보자.

interface Animal {
  name: string;
  age: number;
  jump(): string;
}

class Dog implements Animal {
  name: string;
  age: number;

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }

  jump(): string {
    return `${this.name}이 점프를 한다.`;
  }

  // 추가로 정의해주는 것은 괜찮다.
  dance() {}
}

Animal 인터페이스를 객체지향 관점에서 클래스로 선언할 수 있다. implements 키워드를 사용하면 된다.

주의할 점은 인터페이스에 정의되어 있는 모든 요소들이 클래스 안에 똑같이 정의되어 있어야 한다

여러 개의 인터페이스 #1

interface Pet {
  legsCount: number;
  bark(): void;
}
interface Animal {
  name: string;
  age: number;
  jump(): string;
}

class Cat implements Animal, Pet {
  name: string;
  age: number;

  // Pet
  legsCount: number;
  constructor(name: string, age: number, legsCount: number) {
    this.name = name;
    this.age = age;
    this.legsCount = legsCount;
  }
  // Animal
  jump(): string {
    return `${this.name}이 점프를 한다.`;
  }

  // Pet
  bark(): void {
    console.log('냐옹');
  }
}

여러 개의 인터페이스를 implement할 수도 있다. 하지만 implement한 타입의 모든 프로퍼티를 정의해줘야 한다.

여러 개의 인터페이스 #2

type AnimalAndPet = Animal & Pet;

class Cat2 implements AnimalAndPet {
  name: string;
  age: number;

  // Pet
  legsCount: number;
  constructor(name: string, age: number, legsCount: number) {
    this.name = name;
    this.age = age;
    this.legsCount = legsCount;
  }
  // Animal
  jump(): string {
    return `${this.name}이 점프를 한다.`;
  }

  // Pet
  bark(): void {
    console.log('냐옹');
  }
}

타입을 인터섹션하여 하나의 타입으로 정의한 뒤, 그 타입을 implement 해줄 수도 있다.

implement 할 때 주의할 점

interface WrongInterface1 {
  name: string;
}
interface WrongInterface2 {
  name: number;
}

class Person implements WrongInterface1, WrongInterface2 {
  name: number | string; // X
  name: string; // X
  name: number; // X
}

서로 다른 인터페이스에서 프로퍼티 중복이 없는지 잘 확인해야 한다.

0개의 댓글