Skip to content

인터페이스 (Interfaces)

TypeScript에서 인터페이스는 객체의 구조를 정의하고, 클래스나 객체가 반드시 따라야 할 규칙을 나타낸다. 즉, “이 객체는 어떤 속성과 메서드를 가져야 한다"라는 청사진 역할을 한다.


인터페이스의 특징

  • 객체의 구조를 정의하는 계약서 역할
  • readonly, ?를 통해 속성 제약 가능
  • 함수/메서드 시그니처 정의 가능
  • extends를 통한 확장성과 조합성이 뛰어남
  • 클래스의 implements 키워드와 함께 사용 시, 클래스가 반드시 해당 규격을 지키도록 강제

1. 기본 문법

인터페이스는 interface 키워드를 사용하여 정의한다.
인터페이스 이름은 대문자로 시작하는 것이 관례이다.

ts
interface User {
  속성명: 속성 타입;
  메서드명(): 메서드 반환 타입;
}

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

const userA: User = {
  id: 10,
  name: "Binny",
  isPremium: false,
  someMethod() {
    console.log("some method called");
  },
};

2. type alias vs interface

타입 별칭인터페이스는 모두 객체의 구조를 정의할 수 있지만 몇 가지 차이점이 존재한다.

ts
// type alias
type User = {};

// interface
interface User {}
  • type alias: 객체, 리터럴, 원시값, 유니언, 인터섹션 등 다양한 타입 가능
  • interface: 객체 타입으로 사용해야 한다. 확장에 유리하다.
  • 확장 문법이 다르다.

💡

  • 일반적으로 객체 구조를 정의할 때는 interface
  • 복잡한 타입 조합(유니언, 교차 등)이 필요할 때는 type alias를 자주 쓴다.

3. Readonly & Optional Property

readonly: 수정 불가 속성
?: 선택적 속성

ts
interface User {
  readonly id: number;
  name: string;
  isPremium?: boolean;
}

const testUser: User = {
  id: 100,
  name: "Bin",
};

testUser.id = 200; // 오류: id는 readonly

4. 메서드 정의하기

인터페이스에는 함수 타입도 정의할 수 있다.

예시: 반환값 없음

ts
interface User {
  readonly id: number;
  name: string;
  isPremium?: boolean;
  greet(): void; // 매개변수 X, 반환값 없음
}

const testUser: User = {
  id: 100,
  name: "milou",
  isPremium: false,
  greet() {
    console.log("Hello Milou");
  },
};

testUser.greet(); // Hello Milou
  • Hello Milou 문자열만 출력되고, 별도의 값은 반환되지 않는다.
  • 즉, void 타입 메서드는 결과를 변수에 담으려고 해도 undefined가 된다.
ts
const result = testUser.greet(); // 콘솔 출력: Hello Milou
console.log(result); // undefined

예시: 값 반환

ts
interface User {
  readonly id: number;
  name: string;
  isPremium?: boolean;
  greet(message: string): string; // 매개변수 O, string 반환
}

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

console.log(testUser.greet("Hello")); // Hello, milou
  • 값을 반환하는 함수로 사용한다. 호출 결과를 다른 변수에 담거나 재활용할 수 있다.

💡 Tip

  • (): void → 동작 중심 (로그, DOM 조작, 상태 업데이트)
  • (param: type)→ 값 중심 (계산 결과, 메시지 반환 등)

5. 인터페이스 확장 (Extends)

단일 확장

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

// Interface 확장
interface Student extends Person {
  studentId: number;
}

// Person Interface 사용
const PersonA: Person = {
  name: "Milou",
  age: 21,
};

// Student Interface 사용
const studentA: Student = {
  name: "binny",
  age: 30,
  studentId: 12345,
};

다중 확장

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

interface Employee {
  employeeId: number;
}

// Interface 확장
interface Student extends Person, Employee {
  studentId: number;
}

// Student Interface 사용
const studentA: Student = {
  name: "binny",
  age: 30,
  studentId: 12345,
  employeeId: 23456,
};