Typescript에서 type과 interface의 차이

2023. 2. 16. 19:46WEB.DEV/Typescript

반응형

안녕하세요.
이번 포스팅에서는 Typescript에서 type과 interface의 차이에 대해서 알아보겠습니다.

타입스크립트에서 타입을 정의하는 방법이 2가지가 있는데 바로 type을 사용하는 것과 interface를 사용하는 것입니다.

type Person = {
  name: string;
  email: string;
}

interface Person {
  name: string;
  email: string;
}

대부분의 경우에는 type과 interface를 구분하지 않고 사용을 해도 됩니다.

type과 interface 둘 다 추가 속성과 함께 할당한다면 동일한 오류가 발생을 합니다.

const jim: Person = {
  name: 'jim',
  email: 'jim@gmail.coml',
  verified: false
};
// Person 형식에 verified가 없다는 오류 발생

인덱스 시그니처 역시 type과 interface 둘 다 사용할 수 있습니다.

type dictionary = {[key: string]: string};

interface dictionary {
  [key: string]: string;
}

함수의 타입도 type과 interface 둘다 사용해서 정의할 수 있습니다.

type voidFn = () => void;
const execute: voidFn = () => console.log('type');

interface voidFn {
  (): void;
}
const execute: voidFn = () => console.log('interface');

type과 interface 둘다 제너릭 사용이 가능합니다.

type Value<T> = {
  selectedValue: T;
}

interface Value<T> {
  selectedValue: T;
}

type과 interface 둘다 확장을 할 수 있습니다.

type Jim = Person & { verified: boolean; };

interface Jim extends Person {
  verified: boolean;
}

클래스를 구현할 때도 type과 interface 둘 다 동일한 방법으로 사용이 가능합니다.

class Jim implements Person {
  name: string = 'jim';
  email: string = 'jim@gmail.com';
}

그렇다면 type과 interface의 차이점은 무엇일까요?

union type은 있지만 union interface는 없습니다.

type color = 'primary' | 'secondary' | 'warning';

type은 union type에 추가 속성을 붙인 타입을 만들 수 있지만 interface로는 표현이 불가능합니다.

type Input = {value: string};
type focus = {isFocus: boolean};

type focusRequireInput = Input & focus & {isRequired: boolean};

type은 튜플과 배열을 더 간결하게 표현할 수 있게 해 줍니다.

type Pair = [number, number];
type List = string[];
type StringAndNumbers = [string, ...number[]];

interface는 보강이 가능합니다.(선언병합)

interface Person {
  name: string;
}

interface Person {
  email: string;
}

const jim: Person = {
  name: 'jim',
  email: 'jim@gmail.com'
};

여기까지 Typescript의 type과 interface의 차이점을 간략하게 알아보았습니다.
부족한 점이나 추가 필요한 점이 있다면 댓글을 남겨주시면 수정 추가하도록 하겠습니다.

부족한 글 읽어주셔서 감사합니다💛

728x90
반응형