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?