[Typescript] type과 interface의 차이점

eunji·2022년 10월 24일
0

typescript를 사용하는데 타입을 선언하는 방식은 2가지가 있다. 바로 type과 interface인데 두가지의 차이점이 무엇인지 알아보고자 한다.

type 선언

type NameType={
	firstName:string;
    lastName:string;
}

const person1:NameType={
	firstName:'Tom';
    lastName:'Cruise;
}

interface 선언

interface NameType{
	firstName:string;
    lastName:string;
}

const person1:NameType={
	firstName:'Tom';
    lastName:'Cruise;
}

type 과 interface의 차이

확장하는 방법

type같은 경우 확장할 때 '&'기호를 사용하여 타입확장을 한다.

type PersonType={
	name:string;
    age:string;
}

type StudentType=PersonType & {
	school:string
}

interface같은 경우 extends키워드를 사용하여 타입확장을 한다.

interface PersonType{
	name:string;
    age:string;
}

interface StudentType extends PersonType{
	school:string
}

computed property에서의 사용

computed property란 표현식을 이용해 객체의 키 값을 정의하는 문법이다.

type name = 'firstName'|'lastName';

type Nametype={
	[key in name]:string; // 가능 
}

interface NameType={
	[key in name]:string; // 불가능 
}

선언가능한 타입

type같은 경우 primitive, union, tuple, object타입 모두 선언이 가능하지만 interface같은 경우 object타입만 선언이 가능하다.

type NameType='firstName'|'lastName'; 

type Nametype= FirstNameType | LastNameType;

type NameType=[string, number];

함수 선언 방법

type getList=(id: number) => void; 

interface getList{
	(id:number): void;
}

interface에서만 가능한 것

선언적 확장 : 같은 이름으로 선언하여 새로운 속성을 추가하는 것

type NameType={
	firstName:string;
}

type NameType={
	lastName:string; // 불가능 
}

interface NameType{
	firstName:string;
}

interface NameType{
	lastName:string; // 가능 

}

그래서 나의 선택은?

이 두가지의 차이점을 찾아 제대로 이해하고 최선의 선택을 하기 위해 자료 조사를 많이 하였다. 결론적으로 나는 프로젝트에 'interface'를 사용하기로 하였는데 그 이유로는 확장성이 있다. 사실 두가지의 차이점이 크게 있다고는 할 수 없다. 앞으로 결정적인 차이점이 나타날 수 있지만 현재는 없기 때문에 한가지로 통일하기 위하여 interface를 사용할 예정이다.

profile
프롱이

0개의 댓글