Interface vs Type

이민서·2025년 1월 21일

TypeScript

목록 보기
2/7

Interface

객체의 구조를 정의하기 위해 사용

interface User {
  name: string;
  age: number;
  sayHello(): void;
}

// 인터페이스 구현
class Customer implements User {
  constructor(public name: string, public age: number) {}
  
  sayHello() {
    console.log(`Hello, I'm ${this.name}`);
  }
}

필수 속성 외 제공되지 않아도 사용이 가능한 선택적 속성이 있는데, 선택적 속성은 ? 을 통하여 정의할 수 있다.

interface user {
	id:number;
	name:string;
	info?:string   // 선택적 속성
}

주요 특징

//type Character = {
//	nickName:string;
//}
//type BirdCharacter = { fly:number } & Character

interface Character {
	nickName:string;
}
interface BirdCharacter extends Character { 
	fly:number;
}

Type

데이터의 타입을 정의하기 위해 사용

type StringOrNumber = string | number;

type Point = {
  x: number;
  y: number;
};

// Union 타입
type Status = "pending" | "completed" | "failed";

// 튜플 타입
type Coordinates = [number, number];

주요 특징

  • Union, intersection 타입 정의 가능
    👉 Union type, Intersection type
  • 튜플과 배열 타입을 보다 명확하게 정의
  • 타입 별칭으로 사용
  • 유틸리티 타입과 함께 사용하기 좋음

Interface vs Type

  • 확장 방식
// Interface - extends 사용
interface Animal {
  name: string;
}
interface Dog extends Animal {
  bark(): void;
}

// Type - & 사용
type Animal = {
  name: string;
}
type Dog = Animal & {
  bark(): void;
}
  • 선언 병합
// Interface - 가능
interface User {
  name: string;
}
interface User {
  age: number;
} // name, age 모두 포함

// Type - 불가능
type User = {
  name: string;
}
type User = { // Error
  age: number;
}

0개의 댓글