[typescript] 타입스크립트의 인터페이스와 추상 클래스의 활용 방법

일반적으로 타입스크립트에서 인터페이스추상 클래스는 코드의 유지보수성과 확장성을 향상시키는 데 사용됩니다. 이들은 코드의 일관성을 유지하고 재사용 가능한 구조를 정의하는 데 유용하며, 다형성을 구현하는 데에도 도움을 줍니다. 이번 글에서는 각각의 기능과 간단한 예제를 통해 어떻게 활용되는지 알아보겠습니다.

목차

인터페이스

인터페이스는 타입스크립트에서 구조를 정의하며, 객체가 해당 인터페이스의 요구사항을 충족하는지 검증합니다. 이를 통해 특정 형태나 구조를 갖춘 타입을 명시하고자 할 때 사용됩니다.

기본적인 인터페이스

interface Shape {
  name: string;
  numberOfSides: number;
}

function printShape(shape: Shape) {
  console.log(`This shape is ${shape.name} and has ${shape.numberOfSides} sides.`);
}

let rectangle: Shape = { name: 'rectangle', numberOfSides: 4 };
printShape(rectangle); // Output: This shape is rectangle and has 4 sides.

선택 속성을 가진 인터페이스

interface Car {
  brand: string;
  model: string;
  year?: number;  // Optional property
}

function printCarInfo(car: Car) {
  console.log(`Car: ${car.brand} ${car.model}, Year: ${car.year || 'unknown'}`);
}

let myCar: Car = { brand: 'Toyota', model: 'Corolla' };
printCarInfo(myCar); // Output: Car: Toyota Corolla, Year: unknown

추상 클래스

추상 클래스는 타입스크립트에서 추상화를 통해 공통된 속성 및 메서드를 정의할 수 있게 해줍니다. 추상 클래스는 직접 인스턴스화될 수 없지만, 이를 상속하여 자식 클래스에서 구현할 수 있습니다.

간단한 추상 클래스 예제

abstract class Animal {
  abstract makeSound(): void;
}

class Dog extends Animal {
  makeSound() {
    console.log('Woof! Woof!');
  }
}

class Cat extends Animal {
  makeSound() {
    console.log('Meow! Meow!');
  }
}

let dog = new Dog();
dog.makeSound(); // Output: Woof! Woof!

let cat = new Cat();
cat.makeSound(); // Output: Meow! Meow!

이상으로 타입스크립트에서의 인터페이스추상 클래스 활용 방법에 대해 살펴보았습니다. 이러한 개념들을 잘 활용하여 코드의 일관성과 재사용성을 향상시킬 수 있습니다.