개발이야기
[TypeScript] type과 interface는 뭐가 다른건데!
미누라니까요
2025. 3. 25. 14:25
728x90
반응형
SMALL
최근 프로젝트를 하던 중 다른 팀원의 코드에 interface를 사용하여 props를 받는 부분을 보았다.
typescript를 아직 많이 사용해보지 않아 기본적으로 type을 사용하고 있었는데, 이 코드를 보고 interface와 type은 각각 어떨 때 사용하는거지 ? 라는 의문이 들어 찾아보게 되었다.
type 을 사용하는 경우
단순히 원시 값, 튜플(tuple) 등을 선언할 때!
type Name = string;
- type은 일반적으로 모든 선언에 사용할 수 있다.
- 선언해둔 것을 확장할 수 없다.
type Student = {
name:string;
stdNo:string;
};
type Student = {
age: number;
}; // Error
또한 type으로 선언한 것들은 선언적 확장(이후에 같은 객체 타입을 작성하면 추가되는 방식)이 불가능하다.
- type은 기본적으로 확장 불가능하지만, &를 사용하여 확장이 가능하다.
type Student = {
name: string;
age: number;
};
type ElementStudent = Student & {
school : string
}
interface를 사용하는 경우
보통 객체 타입을 선언할 때는 대부분 interface를 사용한다.
interface Student = {
name:string;
stdNo:string;
};
- interface는 extends 키워드를 통해 확장할 수 있다!!
interface Student = {
name:string;
stdNo:string;
};
interface ElementStudent extends Student = {
grade:number;
};
const e1 : ElementStudent = {
name:'minwoo',
stdNo:'2022',
grade:6,
};
- 또한 interface는 선언적 확장이 가능하다!
interface Student = {
name:string;
stdNo:string;
};
interface Student = {
school:string;
};
타입이 계속 확장할 수 있다면 interface를 사용하는 편이 낫다!!
결론적으로, 객체 혹은 확장할 수 있는 타입을 선언하려면 Interface를 사용하고, 나머지 경우에는 type을 고려해보면 좋을 거 같다.
728x90
반응형
LIST