Type vs Interface: Which Should You Use In 2023?

Untitled

간단한 설명

‘extends’와 같은 인터페이스의 특정 기능이 필요할 때까지는 기본적으로 type을 사용해야 합니다.

전체 설명

TypeScript는 다른 객체에서 확장되는 객체를 정의하기 위한 일급 프리미티브인 인터페이스를 제공합니다.

인터페이스는 타입스크립트의 첫 번째 버전부터 존재해 왔습니다. 인터페이스는 객체 지향 프로그래밍에서 영감을 얻었으며 상속을 사용하여 타입을 만들 수 있습니다.

interface WithId {
  id: string;
}
 
interface User extends WithId {
  name: string;
}
 
const user: User = {
  id: "123",
  name: "Karl",
  wrongProperty: 123,
// Type '{ id: string; name: string; wrongProperty: number; }' is not assignable to type 'User'.
// Object literal may only specify known properties, and 'wrongProperty' does not exist in type 'User'.
};

그러나 type 키워드를 사용하여 선언하는 타입 alias라는 대체 기능이 내장되어 있습니다. type 키워드는 객체 타입뿐만 아니라 TypeScript에서 모든 종류의 타입을 나타내는 데 사용할 수 있습니다.

문자열 또는 숫자인 타입을 표현하고 싶다고 가정해 봅시다. 인터페이스에서는 그렇게 할 수 없지만 타입에서는 가능합니다.

type StringOrNumber = string | number;
 
const func = (arg: StringOrNumber) => {};
 
func("hello");
func(123);
 
func(true);
// Argument of type 'boolean' is not assignable to parameter of type 'StringOrNumber'.