개발노트

6. [TypeScript] Interface 사용법 (with type과의 차이점) 본문

웹 개발/TypeScript

6. [TypeScript] Interface 사용법 (with type과의 차이점)

mroh1226 2023. 8. 7. 18:22
반응형

Interface

interface Person {
  firstName: string;
  lastName: string;
  fullName(): string;
}

class Employee implements Person {
  constructor(public firstName: string, public lastName: string) {}

  fullName(): string {
    return `${this.firstName} ${this.lastName}`;
  }
}

const emp = new Employee("John", "Doe");
console.log(emp.fullName()); // 출력: John Doe

 

Type으로 했을 때 동일한 소스

type Person = {
  firstName: string;
  lastName: string;
  fullName(): string;
};

class Employee implements Person {
  constructor(public firstName: string, public lastName: string) {}

  fullName(): string {
    return `${this.firstName} ${this.lastName}`;
  }
}

const emp = new Employee("John", "Doe");
console.log(emp.fullName()); // 출력: John Doe

Interface 와 type 차이점

  1. 상속 및 확장 (Extending and Extending Union Types):
    interface는 다른 interface로 확장(상속)될 수 있습니다.
    type은 유니온 타입(Union Types)을 이용하여 확장될 수 있습니다.

  2. Implements vs Extends:
    interface는 클래스가 해당 인터페이스를 구현할 것임을 선언하기 위해 implements 키워드를 사용합니다.
    type은 클래스와 직접 연관되지 않으며, 객체 혹은 다른 타입에 별칭(alias)을 제공하기 위해 주로 사용됩니다.

  3. Computed Properties:
    interface는 계산된 속성(Computed Properties)을 정의할 수 없습니다.
    type은 계산된 속성을 포함한 타입을 정의할 수 있습니다.

  4. Intersection Types:
    interface는 두 개 이상의 타입을 결합하여 새로운 타입을 만드는 교차 타입(Intersection Types)을 정의할 수 있습니다.
    type도 마찬가지로 교차 타입을 정의할 수 있습니다.

  5. Declaration Merging:
    interface는 동일한 이름의 인터페이스를 여러 번 선언하면, TypeScript가 이를 자동으로 병합(Declaration Merging)해줍니다.
    type은 병합되지 않고, 같은 이름의 type 선언이 충돌하면 오류가 발생합니다.

일반적으로, interface는 클래스와 객체의 구조적인 관점에서 사용되며, 주로 공용 API나 라이브러리의 타입 정의에 유용합니다. 반면에 type은 특정 타입에 별칭을 부여하거나, 더 복잡한 유니온 및 교차 타입을 정의할 때 더 효과적일 수 있습니다. 둘 다 상황에 따라 사용될 수 있으며, 프로젝트 요구에 따라 선택하면 됩니다.


Interface implement
implement 받은 class는 해당 interface의 모든 속성, 메서드를 모두 실제 구현을 해야함

interface Person {
  firstName: string;
  lastName: string;
  fullName(): string;
}

class Employee implements Person {
  constructor(public firstName: string, public lastName: string) {}

  fullName(): string {
    return `${this.firstName} ${this.lastName}`;
  }
}

const emp = new Employee("John", "Doe");
console.log(emp.fullName()); // 출력: John Doe

 

 

Interface 상속:

Interface끼리 extends로 상속가능함

interface Animal {
  name: string;
  makeSound(): void;
}

interface Dog extends Animal {
  breed: string;
}

const myDog: Dog = {
  name: "Buddy",
  breed: "Labrador",
  makeSound() {
    console.log("Woof Woof!");
  },
};


Interface의 Declaration Merging:

여러번선언해도 병합하여 사용 가능함

interface Car {
  brand: string;
}

interface Car {
  model: string;
}

const myCar: Car = {
  brand: "Toyota",
  model: "Camry",
};

 

반응형
Comments