13. 타입과 인터페이스 차이

ClassBinu·2024년 4월 14일

기본 형식

// 이렇게 타입을 선언하는 걸 타입 별칭이라고 함.(type alias)
type TState = {
  name: string;
  capital: string;
};

interface IState {
  name: string;
  capital: string;
}

타입에 T, I를 붙이는 건 요즘은 지양하는 추세

차이

유니온

유니온 타입은 있지만 유니온 인터페이스는 없다.

type AorB = 'a' | 'b';

확장

인터페이스는 타입을 확장할 수 있지만, 유니온은 할 수 없다.

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

interface Employee extends Person {
    salary: number;
}

const employee: Employee = {
    name: "John",
    age: 30,
    salary: 50000
};

보강(augment)

인터페이스는 보강이 가능
(선언 병합)

보강은 '확장성'이다.

// 초기 인터페이스 정의
interface User {
    name: string;
    age: number;
}

// 같은 이름의 인터페이스로 보강
interface User {
    email: string;
}

// User 인터페이스는 이제 name, age, email 속성을 모두 포함
const user: User = {
    name: "Alice",
    age: 25,
    email: "alice@example.com"
};

만약 type으로 보강 효과를 하려면 이런식으로 새로운 타입을 지정해야 함.

type TState = {
  name: string;
  capital: string;
};

type TState2 = {
  age: number;
};

type TState3 = TState & TState2;

타입, 인터페이스 사용을 결정하는 큰 요소 중 하나는 객체 내 타입의 보강 필요 여부에 따라 결정하면 됨.
단, 이때의 보강은 프로젝트 내부에서 필요성이 아니라, 외부 프로젝트와 함께 쓸 때 유용함.

0개의 댓글