본문 바로가기
TypeScript

[TypeScript]Interface VS Type 간단 비교

by hans-j 2024. 7. 30.

📢📢인터페이스와 타입의 차이점!!!

 

우선 한 개 씩 알아보자


첫 타자, 인터페이스

 

인터페이스란


객치 구조를 정의하는 역할을 한다. 다시 말해서 특정 객체가 가져야하는 속성과 메서드의 집합을 인터페이스로 정의하여 객체가 그 구조를 따르게 함!

 

쉽게 말해서 객체와 객체들 간의 의사소통을 위해 규격을 정해놓는 것 like a 계약서.

 

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

 

인터페이스명은 대문자로 짓는다.


다음 타자, 타입


타입이란

간단히 말해서 어떤 데이터를 담을때, 어떤 모습의 데이터를 담을지 정하는것.

  type StudentType {
    age: number;
    name: string;
  }

 

위의 타입은 number자료형만을 데이터타입으로 사용할 것을 선언함.

PositionType이라는 타입에 string 문자열을 넘기면 에러발생.


 

그래서 둘의 공통점은?!

클래스에서 구현이 

그렇다 . 가능하다.

 

둘 다 클래스에서 구현이 가능하다

  class Information1 implements StduentType {
   	age: number;
   	name: string;
  }
  
  class Information2 implements StduentInterface {
 	age: number;
    	name: string;
  }

 


또한 둘 다 객체 형태로 만들 수 있다.

  const obj1: StudentType = {
    age: number;
    name: string;
  };
  
  const obj2: Studentface = {
    age: number;
    name: string;
  };

 


또한 둘 다 확장을 할 수 있다.

Interface는 extends를 이용해서 확장

interface GenderInterface {
	gender: string;
}

interface StudentInterface extends GenderInterface{
	name : string;
    	age : number;
}

const student: Student = {
	gender : 'female',
        name : 'Hans',
        age : 65
}

 

 

Type은 인터렉션 타입(&)으로 확장

type StudentName = { name : string };
type Information  = StudentName & { gender : string};

let student: Information = { name : 'Hans', gender: 'female'};

 


 

그래서 둘의 차이점은?!

 

타입은 변경할 수 있지만, 인터페이스는 안됨.

 

Interface는 이미 선언된 상태에서도 추후에 추가를 하여 merge하는 것이 가능하지만!!!

 

Type은 기존타입과 별도의 타입을 같이 '묶는' 개념이다. merge가 아님.

 


 

그래서 언제 쓰는게 좋다고?

 

특정한 규격을 정의하는것 혹은 이규격을 통해서 어떤것을 정의한다면  -> 인터페이스가 더 적절

어떤 데이터를 담을때, 어떤 모습의 데이터를 담을지 정하는것이라면 -> 타입이 더 적절

 


 

함께 참고하면 좋은 블로그 글

 

https://inpa.tistory.com/entry/TS-%F0%9F%93%98-%ED%83%80%EC%9E%85%EC%8A%A4%ED%81%AC%EB%A6%BD%ED%8A%B8-%EC%9D%B8%ED%84%B0%ED%8E%98%EC%9D%B4%EC%8A%A4-%F0%9F%92%AF-%ED%99%9C%EC%9A%A9%ED%95%98%EA%B8%B0

 

📘 타입스크립트 인터페이스 활용 💯 총정리

타입스크립트 Interface 인터페이스는 자바(JAVA)를 배운 분들은 매우 익숙하면서도 반가운 단어일 것이다. 다만 자바에서의 인터페이스는 추상 메소드와 상수만을 정의한 클래스를 위주로 다루지

inpa.tistory.com