Multiple Return Values in TypeScript

TypeScript supports returning multiple values from a function using tuples. This feature is often used to return both a result and an error value from a function.

// The [number, number] in this function signature shows that
// the function returns a tuple of 2 numbers.
function vals(): [number, number] {
    return [3, 7];
}

function main() {
    // Here we use destructuring assignment to get the 2 different
    // return values from the function call.
    const [a, b] = vals();
    console.log(a);
    console.log(b);

    // If you only want a subset of the returned values,
    // you can use the rest operator to ignore some values.
    const [, c] = vals();
    console.log(c);
}

main();

To run the program:

$ ts-node multiple-return-values.ts
3
7
7

In TypeScript, we use tuples to return multiple values from a function. The destructuring assignment allows us to easily assign these returned values to individual variables. If we want to ignore some of the returned values, we can use the rest operator (represented by commas without a variable name) in the destructuring assignment.

This pattern is commonly used in TypeScript for functions that might fail, where you’d return a tuple of [result, error]. The caller can then check if the error is null to determine if the operation was successful.

Next, we’ll look at how TypeScript handles functions with a variable number of arguments.