Borislav Hadzhiev
Thu Mar 03 2022·2 min read
Photo by Nathan Dumlao
To return multiple values from a function in TypeScript, group the values in
an array and return the array, e.g. return [myValue1, myValue2] as const
. You
can then destructure and use the values the function returns.
function getValues() { const str = 'hello'; const num = 100; return [str, num] as const; } // 👇️ const result: readonly ["hello", 100] const result = getValues(); const [str, num] = getValues(); console.log(str.toUpperCase()); // 👉️ "HELLO" console.log(num.toFixed(2)); // 100.00
We declared a function that returns multiple values by grouping them in an array.
Notice that the type of the result
variable (and the function's return type)
is ["hello", 100]
.
The as const
syntax is called a
const assertion
in TypeScript.
The const assertion sets the function's return type to be
readonly ["hello", 100]
, which is exactly what we want.
Let's look at the function's return type if we omit the const assertion.
function getValues() { const str = 'hello'; const num = 100; return [str, num]; } // 👇️ const result: (string | number)[] const result = getValues(); const [str, num] = getValues(); // 👇️ Now str is string or number // and num is string or number
Now that we've removed as const
, the function is typed to return an array
containing strings or numbers.
This is not great, because when we
destructure
the values from the array into the str
and num
variables, they are typed as
string | number
.
The string | number
syntax is called a
union type
in TypeScript. A union type is formed from combining two or more other types.
You could get around this by explicitly setting the function's return type to a
tuple containing a string
and a number
.
function getValues(): [string, number] { const str = 'hello'; const num = 100; return [str, num]; } // 👇️ const result: [string, number] const result = getValues(); const [str, num] = getValues();
We've explicitly typed the function to return a tuple, where the first element is a string, and the second - a number.
str
and num
variables, they are typed correctly.The syntax with the square brackets on the left-hand side of the assignment is called destructuring.
const [a, b] = ['hello', 'world']; console.log(a); // 👉️ "hello" console.log(b); // 👉️ "world"
An easy way to think about it is - we are assigning the elements of the array to variables. Note that the order of assignment and the order of the values in the array is the same.
If you don't want to use destructuring, you can explicitly access the values by using bracket notation.
function getValues() { const str = 'hello'; const num = 100; return [str, num] as const; } // 👇️ const result: [string, number] const result = getValues(); const str = result[0]; const num = result[1];