윤시의 블로그

[TypeScript] interface 문법, &(intersection) 본문

TypeScript

[TypeScript] interface 문법, &(intersection)

yo09 2025. 3. 3. 17:02

1. interface 문법

interface는 객체 타입을 정의할 때 사용한다. 객체 자료형의 타입을 보다 편리하게 지정할 수 있다.

interface Square {
	color : string;
	width : number;
}

let 네모: Square = { color : 'red', width : 100 };
  • type alias와 유사한 기능을 제공한다.
  • 대문자로 시작하며 { } 안에 타입을 명시한다.

 

1.1 interface의 장점 : extends

interface는 다른 인터페이스를 확장(상속)할 수 있다.

예를 들어, Stundent와 Teacher 인터페이스를 만들 때 중복 속성을 줄이기 위해 extendf 사용

interface Student {
	name : string;
}

interface Teacher extends Student {
	age : number;
}
  • Teacher는 Student를 상속받아 name과 age 속성을 가진다.

 

1.2 type alias와의 차이점

type alias는 타입을 정의하는 방법이며, interface와 비슷한 기능을 제공하나 몇 가지 차이점이 있다.

  1. interface의 확장 방법
    • extends를 사용함.
    interface Animal {
    	name : string;
    }
    interface Cat extends Animal {
    	legs : number;
    }
    
  2. type의 확장 방법
    • & 연산자(intersection)를 사용해 두 객체를 합침.
    type Animal = {
    	name : string;
    };
    type Cat = Animal & { legs: number };
    
  3. 중복 선언
    3.1 interface 중복 선언 허용 → 속성이 병합됨
interface Animal {
  name: string;
}

interface Animal {
  legs: number;
}

// 병합된 결과:
const animal: Animal = { name: "Tiger", legs: 4 }; // 가능


    3.2 type 중복 선언 불가

type Animal = {
  name: string;
};

type Animal = {
  legs: number;
}; // 에러 발생: Duplicate identifier 'Animal'.

 

 

4. 유니온 타입 및 기타 타입 지원 여부

  • type alias는 유니온 타입, 튜플, 기타 타입들을 정의할 수 있음.
  • interface는 객체 타입만 정의 가능.
// Type alias로 유니온 타입 정의
type ID = string | number;

const userId: ID = 123; // 가능
const anotherUserId: ID = "abc"; // 가능

// Interface로 유니온 타입 정의 (오류)
interface ID = string | number; // 오류 발생

➡️ 결론: 유니온 타입이나 튜플을 정의해야 한다면 type alias를 사용해야 함.

 

 

interface와 type 선택 기준

  1. 객체 타입을 정의할 때는 interface를 사용하는 것이 더 일반적임.
    • 이유: 중복 선언 병합이 가능하고, API 설계에서 객체 구조를 확장하기에 적합.
    • 예: 외부 라이브러리나 API를 설계할 때 주로 사용.
  2. 복잡한 타입 정의(유니언, 튜플, 원시값 등)가 필요한 경우에는 type을 사용함.
    • 이유: type은 더 유연한 타입 정의를 제공하며, 객체 외에도 다양한 구조를 표현할 수 있음.

객체 구조를 정의하고 확장하거나 병합할 일이 많다면 → interface를 추천!

  • 코드의 일관성이 높아지고 가독성이 좋아짐.

다양한 타입(유니온, 튜플, 복잡한 타입)을 정의해야 한다면 → type alias를 추천!

  • 보다 유연하게 타입을 작성할 수 있음.

이해하기 쉽게 요약하면

  • interface는 주로 "객체 타입 정의"에 특화되어 있고, 확장/병합에 강점이 있음.
  • type alias는 "모든 타입 정의"에 유연하지만 확장성은 인터페이스만큼 좋지 않음.

2. Intersection (&)

& 연산자를 사용해 여러 타입을 결합할 수 있다.

interface Student {
  name: string;
}
interface Teacher {
  age: number;
}

let person: Student & Teacher = { name: 'kim', age: 90 };

주의점

  • 속성 이름이 동일하더라도, 타입이 다르면 에러 발생함
interface Animal {
  name: string;
}
interface Dog {
  name: number;
}

let 변수: Animal & Dog = { name: '멍멍' }; // 에러 발생!