Language/TypeScript

[TS] Syntax | 03. 함수 타입 명시하기

Rayi 2024. 6. 24. 22:36

함수를 선언할 때는 매개변수와 반환값의 타입을 명시해줍니다.

마찬가지로 코드에서 충분히 추론이 가능하다면 반환값의 타입은 명시하지 않아도 됩니다.

const stock: { [id: string]: number } = {
  c001: 3,
  c002: 1,
};
const cart: string[] = [];

function getItem(item: string): string {
  return item;
}

매개변수의 디폴트값은 다음과 같이 나타냅니다.

function addToCart(id: string, quantity: number = 1) {
  if (stock[id] < quantity) {
    return false;
  }

  stock[id] -= quantity;
  for (let i = 0; i < quantity; i++) {
    cart.push(id);
  }

  return true;
}

가변변수는 다음과 같이 나타냅니다.

function addManyToCart(...ids: string[]) {
  for (const id of ids) {
    addToCart(id);
  }
}

함수를 객체의 property에 포함할 때는 다음과 같이 화살표 표기법(=>)으로 타입을 명시합니다.

const mall: {
  stock: { [id:string]: number }
  cart: string[];
  addToCart: (id:string, quantity?:number) => boolean;
  addManyToCart: (...ids: string[]) => void;
} = {
  stock: {
    c001: 3,
    c002: 1,
  },
  cart: [],
  addToCart,
  addManyToCart,
}
728x90