JacopoStanchi
JacopoStanchi

Reputation: 2146

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.

Upvotes: 3

Views: 8463

Answers (2)

Rajiv Punjabi
Rajiv Punjabi

Reputation: 512

The return type is being inferred as an (string | number)[]. To infer as a Tuple you can use const assertions. TS Documentation for const assertion

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

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

Upvotes: 1

Linda Paiste
Linda Paiste

Reputation: 42198

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

Upvotes: 6

Related Questions