728x90

TypeScript에서 type과 interface에 대한 차이를 살펴보겠습니다.

기본적인 사용 방법

기본적으로 type과 interface을 사용해 타입을 정의하고 지정하는 방법은 같습니다.

interface IStudent {
id: number;
name: string;
}
type TStudent = {
id: number;
name: string;
};
const interfaceStudent: IStudent = {
id: 0,
name: 'name',
};
const typeStudent: TStudent = {
id: 0,
name: 'name',
};

타입을 확장하는 방법

type과 interface는 타입을 확장하는 방법에 차이가 있습니다.

type은 & 연산자, interface는 extends 키워드를 이용합니다.

interface IStudent2 extends IStudent {
age: number;
}
type TStudent2 = TStudent & {
age: number;
};

또한, interface의 경우 동일한 이름으로 다시 interface를 정의해 확장하는 것이 가능합니다.

interface IStudent {
id: number;
name: string;
}
interface IStudent {
age: number;
}

type은 동일한 이름으로 다시 선언할 수 없습니다.

type vs interface

type과 interface를 구분해서 사용해야 할 필요가 있을까요? 대부분의 경우에는 구분하지 않고 사용해도 괜찮을 것입니다.

interface IHttpHeader {
Accept: string;
Cookie: string;
};
type THttpHeader = {
Accept: string;
Cookie: string;
};
function send(headers: Record<string, string>) {
return headers;
}
const hdrs = {
Accept: 'text/html',
Cookie: '',
};
send(hdrs as THttpHeader); // OK
send(hdrs as IHttpHeader); // ERROR

위 코드를 보면, type으로 선언한 hdrs는 Record<string, string>에 넘길 때 에러가 발생하지 않지만, interface로 선언한 hdrs는 에러가 방생합니다.

Argument of type 'IHttpHeader' is not assignable to parameter of type 'Record<string, string>'.
Index signature is missing in type 'IHttpHeader'.

에러의 내용은 위와 같으며(깃허브 이슈), 간단히 다음과 같은 규칙을 갖고 있습니다.

  • type은 generic type에 저장할 수 있습니다.
type GenericType = { [x: string]: number };
type NormalType = { x: number };
const normalType: NormalType = {
x: 1,
};
const genericType: GenericType = normalType; // no error
  • interface는 generic interface에 저장할 수 없습니다.
interface GenericInterface {
[x: string]: number;
}
interface NormalInterface {
x: number;
}
const normalInterface: NormalInterface = { x: 1 };
const genericInterface: GenericInterface = normalInterface; // error
  • interface는 generic interface를 확장할 수 있습니다.
interface GenericInterface {
[x: string]: number;
}
interface NormalInterface extends GenericInterface {
x: number;
}
const normalInterface: NormalInterface = { x: 1 };
const genericInterface: GenericInterface = normalInterface; // no error
  • type은 generic interface에 저장할 수 있습니다.
interface GenericInterface {
[x: string]: number;
}
type NormalType = { x: number };
const normalType: NormalType = { x: 1 };
const genericInterface: GenericInterface = normalType; // no error
  • interface는 generic type에 저장할 수 없습니다.
type GenericType = { [x: string]: number };
interface normalInterface {
x: number;
}
const normalInterface: normalInterface = { x: 1 };
const genericType: GenericType = normalInterface; // error

때문에 현재 interface를 사용하는 것은 의도치 않은 에러를 만날 수 있습니다.

해당 문제를 개선하기 위해 이슈 제안 및 PR이 활발하게 이뤄지고 있으니, 개선될 가능성도 있을 것입니다.

728x90
728x90