아카이브

[TS] Syntax | 04. Interface 본문

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);
728x90
Comments