프로그래밍/TypeScript

[TypeScript] type과 interface의 차이

싯타마 2023. 1. 6. 09:27

1. 서론

 

TypeScript에서는 타입을 지정하는 방식인 type과 interface, 이렇게 2가지 방법이 있다. 2가지 방법은 어떤 차이가 있고 떠 어떤 것을 사용해야 하는지 알아보자.

 

2. type과 inteface의 공통점

 

일반적인 사용법은 비슷하다. 하지만 인터페이스는 객체에서만 사용이 가능하다는 점을 볼 수 있다.

 

또한 두 방법은 인덱스시그니쳐, 함수 타입, 제내릭, 확장이 가능하다.

 

 

1) 사용방법

// 타입선언
type NumberType = {
  x: number;
  y: number;
}

// 인터페이스 선언
interface NumberInterface {
  x: number;
  y: number;
}

const object1: NumberType = {
  x: 10,
  y: 5,
}

const object2: NumberInterface = {
  x: 20,
  y: 10,
}

 

2) 인덱스 시그니쳐(Index Signiture)

type TestType = {
  [key:string]: string
}

interface TestInterFace {
  [key:string]:string
}

인덱스시그니쳐 참고사이트:

https://developer-talk.tistory.com/297

 

[TypeScript]인덱스 시그니처(Index Signature) 사용 방법

인덱스 시그니처(Index Signature)이란? 인덱스 시그니처(Index Signature)는 { [Key: T]: U } 형식으로 객체가 여러 Key를 가질 수 있으며, Key와 매핑되는 Value를 가지는 경우 사용합니다. 이번 포스팅에서는

developer-talk.tistory.com

 

3) 제네릭(Generic)

type GenericType<T> = {
  x: T;
  y: T;
}

interface GenericInterface <T> {
  x: T;
  y: T;
}

 

4) 함수타입(Function)

type FunctionType = (x: number) => number;
interface FunctionInterface {
  (x: number): number;
}

const Test1: FunctionInterface = (n) => {
  if (n === 0) { return 0; }
  if (n === 1) { return 1; }
  return n * Test1(n - 1);
};

const Test2: FunctionType = (x) => {
  if (x === 0) { return 0; }
  if (x === 1) { return 1; }
  return x * Test2(x - 1);
}

 

5. 클래스 및 확장

type TestType = {
  x: number;
  y: number;
};
interface TestInterface {
  x: number;
  y: number;
}

// Extends
interface ExtendInterface extends TestInterface {
  z: number;
}
type ExtendType = TestType & { z: number };

interface TestInterface {
  z: number;
}

이때 interface는 "extends"를 사용하여 확장하고 type은 "&"을 사용하여 확장한다는 차이점이 있다.

 

3. type과 inteface의 차이점

 

1) interface의 선언적 확장(선언 병합)

 

확장하는 방법에서의 차이도 있지만(interface는 "extends" type은 "&") interface는 선언적 확장이 가능하다는 차이점이 있다. 

interface Test {
  name: string;
  age: number;
}
interface Test {
  email: string;
}
const foo: Test = {
  name: 'foo',
  age: 27,
  email: 'testmail@google.com',
};

// error
type Test2 = {
  name: string;
  age: number;
}
type Test2 = {
  email: string;
}
const foo2: Test2 = {
  name: 'foo2',
  age: 27,
  email: 'testmail@google.com',
};

위와 같이 동일한 이름을 interface로 선언하여 자동적으로 하므로 합칠 수 있는 것을 선언적 확장이라고 하며 inteface만 가능하다.

참고사이트: https://typescript-kr.github.io/pages/declaration-merging.html

 

TypeScript 한글 문서

TypeScript 한글 번역 문서입니다

typescript-kr.github.io

 

2) 복잡한 타입(유니온, 원시값, 템플릿 리터럴, 튜플)의 사용

 

type AorB = 'A' | 'B';
type Input = {
  /* ... */
};
type Output = {
  /* ... */
};

interface VariableMap {
  [name: string]: Input | Output;
}

type NamedVariable = (Input | Output) & { name: string };

type names = 'firstName' | 'lastName'

type NameTypes = {
  [key in names]: string
}

// error
interface NameInterface {
  [key in names]: string
}

일반적으로 interface는 복잡한 타입(유니온, 원시값, 템플릿 리터럴, 튜플)의 사용과 확장을 할 수 없다.

반면에 type 키워드는 유니온이 될 수도 있고 매핑된 타입 또는 조건부 타입 같은 고급 기능에 활용되기도 한다.

튜플과 배열 타입과 type 키워드를 이용해 더 간결하게 표현할 수 있다.

 

결론

-  타입과 인터페이스는 각각의 장점이 있기 때문에 상황에 따라 혹은 기호에 따라 선택

- 우선, 속한 팀에서 사용하는 공통의 코드컨벤션에 따라 일관성이 있게 타입과 인터페이스를 선택하여 사용하여야 한다.

- 복잡한 타입을 사용해야 한다면 type을 선택하도록 하고 간단한 객체 타입이라면 interface를 활용하면 좋다.

- api에 대한 타입 선언이 필요하다면 interface를 사용하는 것이 좋다. api가 변경된 될 때 새로운 필드를 병합할 수 있어서 좋다.

- typescirpt 공식문서에서는 일반적인 상황에서는 Interface를 사용하는 것을 추천한다.

참고사이트: https://www.typescriptlang.org/ko/docs/handbook/typescript-in-5-minutes.html

 

Documentation - TypeScript for JavaScript Programmers

Learn how TypeScript extends JavaScript

www.typescriptlang.org

- 여기서 특정 기능이란 복잡합타입이거나 보다 간결하게 작성하고 싶을 때를 의미하는 것 같다.

- 두 가지의 사용법에 대해 여러 가지 의견이 있다. 선택은 자유~

 

성능을 위해 interface의 사용?

https://bny9164.tistory.com/48

 

typescript type과 interface의 차이

typescript를 공부하던 중 어떤 곳에는 type를 쓰고 어떤 곳에는 interface를 써서 정확히 어떤 차이점이 있는지 이해할 수 없었습니다. 그래서 이 부분에 대해 알아보았습니다. interface AnimalInterface { spe

bny9164.tistory.com

React에서는 type이 유리한가?

https://developer-talk.tistory.com/235

 

[React]TypeScript기반 Type Alias vs interface

이번 포스팅에서는 TypeScript 기반의 React 애플리케이션을 개발할 때, Type을 정의하는 방법을 설명합니다. JavaScript는 다른 프로그래밍 언어와는 다르게 변수 또는 객체를 생성할 때, 타입을 정의하

developer-talk.tistory.com

 

'프로그래밍 > TypeScript' 카테고리의 다른 글

[TypeScript] 제네릭(Generic) 사용법  (0) 2022.08.13