Language/TypeScript

[TS] Syntax | 04. Interface

Rayi 2024. 6. 28. 14:09

Interface는 여러 개의 타입 묶음을 하나의 타입으로 취급하는 방법입니다.

 

이는 비슷한 종류의 객체들이 중복되는 타입 묶음들을 공유할 때 하나의 타입으로 간단하게 표현할 수 있도록 합니다.

 

아래 코드는 id, name, price, membersOnly 네 가지 변수에 대한 타입 묶음을 Product라는 하나의 새로운 타입으로 나타내는 interface로 구현했습니다.

interface Product {
  id: string;
  name: string;
  price: number;
  membersOnly?: boolean;
}

새롭게 정의한 Product를 이용하면 같은 객체 타입을 가지는 product1과 product2의 타입선언을 간단하게 표기할 수 있습니다.

const product1: Product = {
  id: 'c001',
  name: 'mug',
  price: 129000,
  membersOnly: true,
};

const product2: Product = {
  id: 'd001',
  name: 'shoes',
  price: 25000,
};

interface는 상속도 가능합니다. 다음과 같이 extends 구문을 이용해 기존에 있던 interface 타입에 새로운 타입을 추가해 다시 정의할 수 있습니다.

enum Size {
  S = 'S',
  M = 'M',
  L = 'L',
  XL = 'XL',
}

interface ClothingProduct extends Product {
    sizes: Size[];
}

const product3: ClothingProduct = {
	id: 'e001',
    name: 'T-shirts',
    price: 19900,
    sizes: [Size.S, Size.M],
};

interface를 이용해 함수의 타입도 정의할 수 있습니다.

 

(input arg: input type) => output type 형식으로 정의하던 타입을

 

(input arg: input type): output type 형식으로 정의할 수 있습니다.

interface PrintProductFunction {
    (product: Product): void;
}
const printProduct: PrintProductFunction = (product) => {
  console.log(`The price of ${product.name} is ${product.price}.`)
}

printProduct(product1);
printProduct(product2);

 

위의 특징을 살벼보면 type 구문과 유사한 역할을 한다는 것을 알 수 있습니다.

 

하지만 interface는 type과 다른 몇 가지 차이점 또한 있습니다.

 

1. 먼저 같은 이름의 서로 다른 타입 선언을 할때, interface는 자동으로 같은 이름의 타입들을 하나로 병합해줍니다.

interface Person {
  name: string;
}

interface Person {
  age: number;
}

// 위의 두 Person 타입은 정의가 다르지만, 이름이 같아 자동으로 합쳐집니다.
const person: Person = { name: string; age: number; }

2. 하지만 type과는 다르게 | 연산자를 사용하여 union 연산을 수행할 수 없습니다. 이 경우 extend를 써서 해결해야 합니다.

type Status = "loading" | "success" | "error"; // type은 가능합니다.

 

자동으로 중복 병합이 된다는 점 때문에 interface는 주로 확장과 병합이 필요한 객체 타입 선언 등에 사용됩니다.

728x90
댓글수0