typescript arguments

Tony·2022년 3월 9일
0

typescript

목록 보기
7/21

javascript의 함수 선언문 방식엔 arguments라는 프로퍼티가 존재한다.
함수로 전달되는 모든 매개변수(argument)를 arguments라는 배열 비슷한 이 프로퍼티를 통해 불러올 수도 있다.
하지만 이는 어떤 타입이 들어올지 몰라서 전혀 안전하지 않다.
실제로 사용된 코드를 본적이 없는데, 책을 읽으면서 알게 되었다.

타입스크립트에서 arguments와 비슷하면서 안전하게 구현할 수 있는 방법이 있는 예제가 있어서 메모하려한다.

function sumByArguments() {
  return Array.from(arguments).reduce((total, n) => total + n, 0);
}

function sum(...numbers: number[]) {
  return numbers.reduce((total, n) => total + n, 0);
}

// console.log(sumByArguments(1, 2, 3)); // error TS2554: Expected 0 arguments, but got 3.
console.log(sum(1, 2, 3)); // 6

출처 : 책 - 타입스크립트 프로그래밍

profile
움직이는 만큼 행복해진다

0개의 댓글