인터페이스( Interfaces )

2025. 6. 5. 13:48Coding Study/Typescript

특정 객체가 어떤 프로퍼티와 메서드를 가져야 하는지 명확하게 제시해주고, 클래스나 객체가 따라야 할 계약(Contract) 역할을 한다. 구현 방법이 아닌 구조의 가이드라인을 제공하며, 확장 및 조합이 매우 용이하다.

1. 인터페이스 기본 문법

interface 키워드를 사용해 정의하며, 속성 이름과 타입을 명시한다. 여러 속성은 세미콜론으로 구분한다. 메서드도 타입과 함께 정의할 수 있다.

interface User {
  id: number;
  name: string;
  isPremium: boolean;
  someMethod(): void;
}

객체에 인터페이스를 적용하려면 해당 구조를 반드시 따라야 한다.

const userA: User = {
  id: 1,
  name: "bill",
  isPremium: false,
  someMethod() {
    console.log("Hello!");
  }
};

만약 프로퍼티가 하나라도 빠지면 타입 오류가 발생한다.

2. Readonly와 Optional 프로퍼티

readonly 키워드로 읽기 전용, ?로 선택적(옵셔널) 프로퍼티를 지정할 수 있다.

interface User {
  readonly id: number;
  username: string;
  isPremium?: boolean;           // optional 적용
}
const testUser: User = {
  id: 100,
  username: "john"
  // isPremium은 선택사항
};

// testUser.id = 200; // 오류! 읽기 전용 프로퍼티

3. 인터페이스의 메서드(함수) 타입 지정

메서드는 시그니처(이름, 파라미터, 반환 타입)를 정의한다. 구현 객체에서는 반드시 해당 시그니처를 따라야 한다.

interface User {
  id: number;
  name: string;
  isPremium: boolean;
  greet(message: string): string;
}

const testUser: User = {
  id: 2,
  name: "nathan",
  isPremium: false,
  greet(message: string) {
    return `${message} ${this.name}`;
  }
};

console.log(testUser.greet("Hello")); // Hello nathan
메서드의 파라미터와 반환 타입이 인터페이스 정의와 다르면 오류가 발생한다.

4. 인터페이스 확장(상속)

extends 키워드를 사용해서 다른 인터페이스의 구조를 상속받을 수 있다.

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

interface Student extends Person {
  studentId: number;
}

const personA: Person = {
  name: "lee",
  age: 20
};

const studentA: Student = {
  name: "kim",
  age: 21,
  studentId: 12345
};

5. 인터페이스 다중 확장

인터페이스는 여러 개의 인터페이스를 동시에 상속받을 수 있다.

interface Employee {
  employeeId: number;
}

interface Student extends Person, Employee {
  studentId: number;
}

const studentB: Student = {
  name: "park",
  age: 22,
  studentId: 67890,
  employeeId: 999
};

 

다중 확장으로 다양한 구조를 유연하게 조합할 수 있다.

 

 

6. Type Alias와 Interface의 차이

< type 과 Interface 사용 기준 >

   객체 구조 위주 : Interface

   유니언, 튜플, 복합타입 : type

 

  • Type Alias는 type 키워드를 사용하고, Interface는 interface 키워드를 사용한다.
  • Type Alias는 객체, 리터럴, 원시값 등 다양한 타입을 정의할 수 있다.
  • Interface는 오직 객체 타입만 정의할 수 있다.
  • 확장(상속) 문법이 다르다.
기능 목적은 거의 같지만, 지원하는 자료형과 확장 방식에서 차이가 있다.
No.
항목
interface type
1) 주요 목적 객체의 구조를 정의하기 위한 것 다양한 타입(유니언, 튜플 등) 정의
2) 확장 방식 extends 키워드로 확장 & 연산자로 확장
3) 중복 선언 가능 (자동으로 병합됨) 불가능 (에러 발생)
4) 표현력 객체 구조에 적합 유니언 타입, 튜플 등 복잡한 타입에 적합
5) 구현 가능성 클래스에서 implements 가능 클래스에서 사용은 가능하지만 implements 불가
 
1) 주요목적 ( interface 는 객체 구조 정의만 가능 )

 

< interface , type 기본구조 >

// interface
interface User {
  name: string;
  age: number;
}

// type
type User = {
  name: string;
  age: number;
};

 

Interface 는 Union type 이 안된다.

type Status = "loading" | "success" | "error"; // 가능
// interface Status = "loading" | "success" | "error"; // ❌ 불가능
 

2) 확장방식

// interface 확장
interface Animal {
  name: string;
}
interface Dog extends Animal {
  breed: string;
}

// type 확장
type Animal = { name: string };
type Dog = Animal & { breed: string };

 

3) 중복선언

 interface 는 중복선언하면 병합되나

 type 은 중복선언이 불가능 하다.

interface Box {
  size: number;
}
interface Box {
  color: string;
}
// 최종적으로 Box는 { size: number; color: string }으로 병합됨

type Box = { size: number };
// type Box = { color: string }; // ❌ 오류 발생 (중복 선언 불가)