본문으로 건너뛰기
Advertisement

TypeScript: 인터페이스와 타입 별칭

1. 인터페이스 (Interface)

객체의 구조를 정의하는 가장 일반적인 방법입니다.

interface User {
readonly id: number; // 읽기 전용
name: string;
age?: number; // 선택적 프로퍼티 (Optional)
}

const user1: User = { id: 1, name: "John" };

2. 타입 별칭 (Type Alias)

특정 타입에 이름을 붙여 재사용할 수 있게 합니다. 복잡한 Union 타입 등을 다룰 때 유용합니다.

type ID = string | number;
type Point = { x: number; y: number };

const myId: ID = 123;

3. Interface vs Type

대부분의 경우 둘 다 사용 가능하지만, 몇 가지 차이가 있습니다.

특징InterfaceType
확장성extends를 통한 상속& (Intersection) 사용
선언 병합동일 이름 선언 시 자동 병합됨불가능 (에러 발생)
사용 범위주로 객체의 구조 정의유니온, 프리미티브 등 모든 타입

4. 함수 타입 정의

함수의 매개변수와 반환 타입을 인터페이스나 타입으로 정의할 수 있습니다.

interface MathFunc {
(x: number, y: number): number;
}

const add: MathFunc = (a, b) => a + b;
Advertisement