[typescript] 타입스크립트에서 인터페이스를 구현하는 방법

타입스크립트는 인터페이스(Interface)를 사용하여 코드의 가독성을 높이고 유지보수를 용이하게 합니다. 인터페이스는 클래스나 객체가 기대되는 속성과 메서드를 명확히 정의합니다. 이번 글에서는 타입스크립트에서 인터페이스를 구현하는 방법에 대해 알아보겠습니다.

단순한 예제

interface IUser {
  name: string;
  age: number;
}

function getUserInfo(user: IUser): void {
  console.log(`Name: ${user.name}, Age: ${user.age}`);
}

let someUser = {
  name: 'Alice',
  age: 30,
  email: 'alice@example.com' 
};

getUserInfo(someUser); // Output: Name: Alice, Age: 30

위 예제에서 IUser 인터페이스를 정의하고, getUserInfo 함수에서 이를 활용하였습니다. 인터페이스를 사용함으로써 someUser 객체의 email 속성이 불일치하는 경우 컴파일 시 에러가 발생합니다.

클래스에서 인터페이스 구현하기

interface Shape {
  color: string;
}

class Square implements Shape {
  sideLength: number;
  color: string;

  constructor(sideLength: number, color: string) {
    this.sideLength = sideLength;
    this.color = color;
  }

  area(): number {
    return this.sideLength * this.sideLength;
  }
}

let square = new Square(5, "red");
console.log(square.area()); // Output: 25

Shape 인터페이스를 구현하는 Square 클래스를 정의한 예제입니다. 클래스가 인터페이스를 구현할 때는 implements 키워드를 사용하여 구현합니다.

인터페이스를 구현함으로써 코드의 일관성과 유지보수성을 향상시킬 수 있습니다. 이를 통해 코드의 안정성을 높이고 오류를 최소화할 수 있습니다.

결론

타입스크립트에서 인터페이스를 사용하여 코드를 작성하면 타입 체크에 도움을 주고 전반적으로 안정적인 코드를 작성할 수 있습니다. 인터페이스를 적절히 활용하여 코드의 가독성을 높이고 유지보수를 용이하게 만들어보세요!