Variadic Functions in TypeScript
Here is the translation of the Go code example to TypeScript, with explanations in Markdown format suitable for Hugo.
Variadic functions can be called with any number of trailing arguments. For example, console.log
in JavaScript (and TypeScript) is a common variadic function.
Here’s a function that will take an arbitrary number of integers as arguments.
Within the function, the type of nums
is equivalent to number[]
. We can call nums.length
, iterate over it with for-of
, etc.
Variadic functions can be called in the usual way with individual arguments.
If you already have multiple arguments in an array, apply them to a variadic function using the spread operator like this.
To run the TypeScript code, put the code in a .ts
file, compile it to JavaScript using tsc
, and then run the compiled JavaScript file.
The output should be:
Another key aspect of functions in TypeScript is their ability to form closures, which we’ll look at next.
Next example: Closures.