Implementing Variadic Function Types in TypeScript
Variadic functions are functions that can accept a variable number of arguments. Implementing them effectively in TypeScript requires understanding how to work with rest parameters and type inference. This challenge will guide you through creating a function that accepts an arbitrary number of numeric arguments, calculates their sum, and provides type safety.
Problem Description
You are tasked with creating a TypeScript function called sumNumbers that accepts a variable number of numeric arguments and returns their sum. The function should be type-safe, ensuring that only numbers are passed as arguments. The function should handle cases with zero, one, or multiple arguments gracefully. The return type should accurately reflect the sum of the numbers.
Key Requirements:
- The function must accept a variable number of arguments.
- All arguments must be of type
number. - The function must return a
numberrepresenting the sum of the arguments. - The function should handle the case where no arguments are provided (returning 0).
Expected Behavior:
sumNumbers()should return0.sumNumbers(5)should return5.sumNumbers(1, 2, 3)should return6.sumNumbers(10, 20, 30, 40)should return100.
Edge Cases to Consider:
- Passing non-numeric arguments (TypeScript should flag this as an error during compilation).
- Large numbers of arguments (performance should be reasonable, though this is not a primary focus).
Examples
Example 1:
Input: sumNumbers()
Output: 0
Explanation: No arguments are provided, so the sum is 0.
Example 2:
Input: sumNumbers(5)
Output: 5
Explanation: A single argument (5) is provided, so the sum is 5.
Example 3:
Input: sumNumbers(1, 2, 3)
Output: 6
Explanation: Three arguments (1, 2, and 3) are provided, so the sum is 6.
Example 4:
Input: sumNumbers(10, 20, 30, 40)
Output: 100
Explanation: Four arguments (10, 20, 30, and 40) are provided, so the sum is 100.
Constraints
- The function must be written in TypeScript.
- The function must be named
sumNumbers. - The function must accept a variable number of arguments of type
number. - The function must return a
number. - The function should not use any external libraries.
- The function should be reasonably performant for a typical number of arguments (up to 100).
Notes
- TypeScript's rest parameters (
...args: number[]) are crucial for implementing variadic functions. - Consider how to handle the case where no arguments are passed to the function.
- Pay close attention to type safety – ensure that only numbers are accepted as arguments. TypeScript's type checking will be your friend here.
- The goal is to create a clean, readable, and type-safe implementation.