1

I have a TypeScript method that I want to let return multiple values, e.g. as follows:

public test0() {
  return [true, "hello", Date.now()];
}

I try to call this method as follows:

let ok: boolean, s: string, d: Date;
[ok, s, d] = this.test0();

This gives the following error:

(TS) Type 'string | number | boolean' is not assignable to type 'boolean'. Type 'string' is not assignable to type 'boolean'.

(likewise for the other two array members)

I also tried object destructuring:

public test1() {
  return { success: true, msg: "hello", date: Date.now() };
}

...

var { success: ok, msg: s, date: d } = this.test1();

This works, but only if ok, s and d are not already declared within the current scope, such as class variables. So, the following does not work:

var { success: this.ok, msg: this.s, date: this.d } = this.test1();

Question: Is there a way to achieve the multiple assignment in one line of code? E.g. by declaring an interface of some sort?

John Pool
  • 87
  • 8

1 Answers1

0

Return a readonly tuple with a const assertion:

function test0(): readonly [true, "hello", number] {
  return [true, "hello", Date.now()] as const;
}

I've added a return type for clarity, but it will be inferred as such simply by adding the as const assertion.

Now, in the following destructure, a, b, and c will have the correct type.

const [a, b, c] = test0();

Playground link

spender
  • 106,080
  • 28
  • 202
  • 324
  • Thanks, I did not know this feature. But unfortunately it does not work when the variables to be assigned are already declared elsewhere in the scope, as in the last code snippet of my question, where they are class variables. – John Pool Feb 03 '21 at 11:41
  • 1
    @JohnPool Destructuring assignment to existing variables or properties has been asked and answered [here](https://stackoverflow.com/questions/27386234/object-destructuring-without-var) and/or [here](https://stackoverflow.com/questions/33742755/object-property-assignment-with-destructuring). Essentially you do not want to use `var`. Is that your primary question? Or is your primary question about heterogeneous arrays and tuples? – jcalz Feb 03 '21 at 16:09
  • Thanks, I wanted to avoid using the `var`: the parentheses around the destructuring assignment give me the result I was looking for! – John Pool Feb 03 '21 at 16:31