Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return multiple values in TypeScript

I want to return multiple values in the return statement of a function in TypeScript. The standard way to do this in JavaScript is to return an array containing the values (source), however, as the values I want to return are of different types, I get an error during compilation:

function fun() {
    return ['hello', 1];
}

let [a, b] = fun();
console.log(a.substring(1));

Error:

test.ts:6:15 - error TS2339: Property 'substring' does not exist on type 'string | number'.
  Property 'substring' does not exist on type 'number'.

6 console.log(a.substring(1));
                ~~~~~~~~~

How to do this?

Thank you for your help.

like image 455
JacopoStanchi Avatar asked Aug 01 '26 14:08

JacopoStanchi


1 Answers

You need to specify that your return is a tuple type, otherwise it will get interpreted as Array<string | number>.

function fun(): [string, number] {
    return ['hello', 1];
}

We say that the returned value is a specific array where the first element is type string and the second is type number. This allows for the correct types to be assigned when destructuring.

let [a, b] = fun();
console.log(a.substring(1)); // logs "ello" - a has type `string`
console.log(b.toPrecision(3)); // logs "1.00" - b has type `number`

Typescript Playground Link

like image 165
Linda Paiste Avatar answered Aug 03 '26 13:08

Linda Paiste



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!