CodeNewbie Community 🌱

Cover image for How to return multiple values in TypeScript?
Tim Mouskhelichvili
Tim Mouskhelichvili

Posted on

How to return multiple values in TypeScript?

When working on a TypeScript function, developers sometimes need to return multiple values. Luckily, TypeScript, just like JavaScript, provides easy ways to accomplish this.

To return multiple values in TypeScript, you can return either:

This article will go through all the different ways of returning multiple values in TypeScript and answer some of the most common questions.

Let's get to it 😎.

How to return multiple values using an array?

One way to return multiple values from a function is to use an array.

Here is an example of how to accomplish it:

const getMultipleValues = (): [ string, number ] => {
    return [ 'Tim', 27 ];
}

const [ myName, age ] = getMultipleValues();

// Outputs: 'Tim', 27
console.log(myName, age);
Enter fullscreen mode Exit fullscreen mode

In this function, we return multiple values using an array.

Also, in the function definition, we have defined a TypeScript tuple containing the returned values' types.

Then, we can use a destructured assignment to get each value individually.

Note: This is a known pattern used by many front-end libraries such as react.

How to return multiple values using an object?

Another option to return multiple values from a function is to use an object.

In the function return block, you simply return an object containing all the values you want.

Here is the same code example as above, but this time, it uses an object:

interface IResponse {
    age: number;
    myName: string;
};

const getMultipleValues = (): IResponse => {
    return {
        age: 27,
        myName: 'Tim'
    };
}

const { myName, age } = getMultipleValues();

// Outputs: 'Tim', 27
console.log(myName, age);
Enter fullscreen mode Exit fullscreen mode

As you can see, we have defined a response interface containing all the values.

Then, like in the example above, we use object destructuring when we need to use the return values.

Final thoughts

As you can see, returning multiple values from a TypeScript function is easy.

You can choose from two options: return an object or an array.

I recommend returning an object when you have a lot of different return values or when you have an optional return value.

When you don't have many return values or are working on a react hook, I recommend returning an array.

typescript return multiple values

Here are other TypeScript tutorials for you to enjoy:

Top comments (1)