How to return multiple values from a TypeScript function

TypeScript (and JavaScript) functions can only return one value, but that value can be an object. To return multiple values from a function, we can return those in an object.

There are two ways of returning an object from a TypeScript function:

Create an object in the function, set the property values and return it

Create an array inline in the return statement. (An array is an object.)

In this example the first element is a string, the second is a number.

function myFunction(): [string, number] {
    return ['Monday', 1];
}

let [a, b] = myFunction();

Async functions

Async functions return promises, so we need to add it to the return type declaration.

async function myFunction(): Promise<[string, number]> {
    return ['Monday', 1];
}

let [a, b] = await myFunction();

Use curly braces

We can use curly braces to enclose the return values, but don’t forget to surround the entire expression with parentheses.

function myFunction(): [string, number] {
    return {'Monday', 1};
}

let ( {a, b} = myFunction() );

Async functions

When an async function returns multiple values in curly braces, we don’t need the parentheses around the entire call expression.

async function myFunction(): [string, number] {
    return {'Monday', 1};
}

let {a, b} = await myFunction();

Leave a comment

Your email address will not be published. Required fields are marked *