본문으로 바로가기

[npm] TypeScript 함수 구현 및 타입 생성

category 공유/npm 2024. 6. 28. 18:58

[npm] TypeScript 함수 구현 및 타입 생성

이번 게시글에서는 TypeScript 함수를 구현하고 타입을 생성해보겠습니다.
그리고 내가 원하는 함수와 타입만 export 하는 것까지 해보도록 하겠습니다.

구현해볼 함수는 특정 상품 중에서 입력된 가격과 이름을 가진 상품을 찾는 함수입니다.
예시를 위한 함수입니다.

폴더 구조 변경

먼저 개발할 때 필요한 폴더 및 파일을 생성해주도록 하겠습니다.

  • 최상위 폴더에 src 폴더 생성
  • src 폴더findProduct.ts , compareName.ts , comparePrice.ts , types.ts , index.ts 파일 생성

위 작업을 마치시면 아래 이미지처럼 됩니다.

함수 구현

  • Product type 정의
// src/type.ts

export interface Product {
  id: number;
  name: string;
  price: number;
}
  • compareName 함수 구현
// src/compareName.ts

import { Product } from "./type";

export function compareName(product: Product, name: string) {
  return product.name === name;
}
  • comparePrice 함수 구현
// src/comparePrice.ts

import { Product } from "./type";

export function comparePrice(product: Product, price: number) {
  return product.price === price;
}
  • findProduct 함수 구현
// src/findPrice.ts

import { compareName } from "./compareName";
import { comparePrice } from "./comparePrice";
import { Product } from "./type";

export function findProduct(
  products: Product[],
  targetPrice: number,
  targetName: string
): Product | undefined {
  return products.find(
    product =>
      comparePrice(product, targetPrice) && compareName(product, targetName)
  );
}

  • npm에 올리고 싶은 함수와 타입 export
// src/index.ts

import { findProduct } from "./findProduct";
import { Product } from "./type";

export { findProduct };
export type { Product };

함수는 너무 간단하니 설명은 생략하겠습니다.

src/index.ts 를 보시면 내가 export 하기 원하는 함수와 타입만 구현해주었습니다.
위 프로젝트 내에서는 compareName, comparePrice 함수를 import 하여 사용할 수 있습니다.
그러나 해당 package를 배포한 후 설치한 사람들은 위 함수는 import 못 하고 src/index.ts에 있는 함수와 타입만 import가 가능합니다.

구현한 함수 실행해보기

ts 파일을 실행하기 위해서는 ts-node 명령어를 사용하여야 합니다.
저 같은 경우 src/index.ts 파일에서 테스트를 하였습니다.

import { findProduct } from "./findProduct";
import { Product } from "./type";

const products: Product[] = [
  { id: 1, name: "Keyboard", price: 50 },
  { id: 2, name: "Mouse", price: 30 },
  { id: 3, name: "Monitor", price: 200 }
];

const product = findProduct(products, 30, "Mouse");

console.log("# product : ", product);

export { findProduct };
export type { Product };

위처럼 간단하게 코드를 구현한 후 터미널에 아래 명령어를 입력하시면 됩니다.

ts-node src/index.ts

위처럼 정상적으로 동작하는 것을 확인하였습니다.

이번 게시글에서는 TypeScript 함수 구현 및 타입 생성을 하였습니다.
혹시 따라오지 못 하신 분은 아래 github 주소를 확인해보세요.

해당 소스코드 : 이동하기

다음 게시글에서는 타입스크립트 프로젝트 배포 전 빌드을 해보겠습니다.

반응형