aotoyae

[TS] interface 인터페이스 본문

TypeScript

[TS] interface 인터페이스

aotoyae 2024. 3. 4. 19:24

 

 

2024.03.04 - [TypeScript] - [TS] enum 열거형 타입

 

[TS] enum 열거형 타입

💡enum 타입에 대해 알아보자. 상품 사이즈처럼 값의 종류를 나열할 수 있는 경우에 쓸 수 있는 타입 let product: { id: string; name: string; price: number; membersOnly?: boolean; sizes: string[]; } = { id: 'c001', name: '

aotoyae.tistory.com

 

💡 interface 에 대해 알아보자.

같은 객체 타입을 계속 만들어 낼때, 기준이 되는 타입을 만들어 사용할 수 있다!

 

const product1: {
  id: string;
  name: string;
  price: number;
  membersOnly?: boolean;
} = {
  id: 'c001',
  name: '주전자',
  price: 129000,
};

const product2: {
  id: string;
  name: string;
  price: number;
  membersOnly?: boolean;
} = {
  id: 'c002',
  name: '커피포트',
  price: 129000,
};

 

객체 타입을 지정할 때 위와 같은 경우

똑같은 타입을 계속 지정해주고 있고, 유지보수하기 좋지 않은 코드다.

이럴 때 사용하는게 interface !

 

interface Product { // 이름의 첫 글자는 대문자로
  id: string;
  name: string;
  price: number;
  membersOnly?: boolean;
}

const product1: Product = { // 타입을 지정하듯이 이름 뒤에 기준이 될 인터페이스를 써준다.
  id: 'c001',
  name: '주전자',
  price: 129000,
};

const product2: Product = {
  id: 'c002',
  name: '커피포트',
  price: 129000,
};

 

interface 에서만 값을 바꿔 에러가 있는지 바로 확인할 수 있다 ~

 

 

😲 interface 는 상속이 가능하다!

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

interface ClothingProduct extends Product { // 위 프로덕트의 값을 그대로 받아와 사이즈만 추가
  sizes: Size[];
}

const product1: ClothingProduct = {
  id: 'c001',
  name: '후드',
  price: 129000,
  sizes: [Size.M, Size.L], // 사이즈 추가
};

const product2: Product = {
  id: 'c002',
  name: '커피포트',
  price: 129000,
};

function printProduct(product: Product) { // 결국 프로덕트에서 가져온 값들이니 Product 타입에 그대로 사용 가능
  console.log(`${product.name}의 가격은 ${product.price}원입니다.`);
}

printProduct(product1); // 후드의 가격은 129000원입니다.
printProduct(product2); // 커피포트의 가격은 129000원입니다.

 

👀 interface 로 함수 타입도 정의할 수 있다.

interface PrintProductFunction { // 함수 파라미터 값과 리턴값의 타입을 정해줌
  (product: Product): void;
}

const printProduct: PrintProductFunction = (product) => {
  console.log(`${product.name}의 가격은 ${product.price}원입니다.`);
};

 

 

~ 활용 ~

interface Entity {
    id: string;
    createdAt: Date;
    updatedAt: Date;
}

interface Monster extends Entity{
  name: string;
  level: number;
  hasGold?: boolean;
  skills: string[];
}

let monster: Monster = {
  id: 'g001',
  name: '고블린',
  level: 22,
  skills: ['태권도', '특공무술'],
  createdAt: new Date(),
  updatedAt: new Date(),
}

console.log(
  `${monster.name}(${monster.id})의 레벨은 ${monster.level}이고,\n` +
    `${monster.hasGold ? '해치우면 골드를 얻는' : '해치워도 골드를 주지 않는'} 몬스터입니다.\n` +
    `${monster.skills.length > 0 ? `가진 능력은 ${monster.skills.join (', ')}입니다.` : ''}`
);

// 고블린(g001)의 레벨은 22이고,
// 해치워도 골드를 주지 않는 몬스터입니다.
// 가진 능력은 태권도, 특공무술입니다.