[TS] Syntax | 04. Interface

2024. 6. 28. 14:09·Language/TypeScript

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

'Language > TypeScript' 카테고리의 다른 글

[TS] Syntax | 05. 타입 별칭(Type Alias)  (0) 2024.06.28
[TS] Type | 02. Literal 타입  (0) 2024.06.28
[TS] type | 01. 열거형(enum)  (0) 2024.06.28
[TS] Syntax | 03. 함수 타입 명시하기  (0) 2024.06.24
[TS] Syntax | 02. 객체 타입 명시하기  (0) 2024.06.24
'Language/TypeScript' 카테고리의 다른 글
  • [TS] Syntax | 05. 타입 별칭(Type Alias)
  • [TS] Type | 02. Literal 타입
  • [TS] type | 01. 열거형(enum)
  • [TS] Syntax | 03. 함수 타입 명시하기
Rayi
Rayi
  • Rayi
    아카이브
    Rayi
  • 전체
    오늘
    어제
    • 분류 전체보기 (276)
      • CS (40)
        • CV (2)
        • PS (34)
      • Reveiw (18)
        • Paper (18)
        • Github (0)
      • ML (8)
        • Pytorch (5)
      • Language (59)
        • Python (8)
        • JavaScript (32)
        • TypeScript (16)
        • C++ (3)
      • IDE (12)
      • Git (13)
      • Frontend (77)
        • React (8)
        • ReactNative (6)
        • SolidJS (20)
        • CSS (12)
      • Backend (44)
        • DB (18)
        • Node.js (11)
      • UI (3)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    figma
    PRISMA
    CV
    CSS
    js
    python
    ps
    ts
    API
    modal
    nodejs
    Git
    Express
    Three
    frontend
    backend
    review
    vscode
    deploy
    postgresql
    DB
    PyTorch
    ReactNative
    expo
    CS
    SOLID
    GAN
    mongo
    react
    ML
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.5
Rayi
[TS] Syntax | 04. Interface
상단으로

티스토리툴바