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.

function sum(...nums: number[]): void {
    console.log(nums, " ");
    let total = 0;
    for (const num of nums) {
        total += num;
    }
    console.log(total);
}

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.

sum(1, 2);
sum(1, 2, 3);

If you already have multiple arguments in an array, apply them to a variadic function using the spread operator like this.

const nums = [1, 2, 3, 4];
sum(...nums);

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.

$ tsc variadic-functions.ts
$ node variadic-functions.js

The output should be:

[ 1, 2 ] 3
[ 1, 2, 3 ] 6
[ 1, 2, 3, 4 ] 10

Another key aspect of functions in TypeScript is their ability to form closures, which we’ll look at next.

Next example: Closures.