3

I have a function that returns a tuple [number, number, number]. I want to use destructuring to assign to my class variables the values returned by the tuple like this:

let [this.a, this.b, this.c] = functionThatReturnsTupleWithThreeNumbers()

but this doesn't work.

Aleksey L.
  • 35,047
  • 10
  • 74
  • 84
MD10
  • 1,313
  • 3
  • 12
  • 35
  • 2
    Does this answer your question? [Is it possible to destructure onto an existing object? (Javascript ES6)](https://stackoverflow.com/questions/29620686/is-it-possible-to-destructure-onto-an-existing-object-javascript-es6) – jonrsharpe Dec 01 '19 at 08:46
  • 1
    no I need to destructre a tuple not an object – MD10 Dec 01 '19 at 08:58

2 Answers2

2

Just remove the let and you're good to go:

class Foo {
    a;
    b;
    c;

    bar() {
        [this.a, this.b, this.c] = [1, 2, 3];
    }
}

const foo = new Foo();
foo.bar();

console.log(foo);

More info here

Typescript playground

Aleksey L.
  • 35,047
  • 10
  • 74
  • 84
1

You need to have the props in your class and destruct your tuple into them:

class MyClass {
    a: number;
    b: number;
    c: number;

    constructor(tuple: ReadonlyArray<number>) {
        [this.a, this.b, this.c] = tuple;
    }
}
marsibarsi
  • 973
  • 7
  • 7
  • @kaki6876, it will work with number[] as well. It is just a good practice because a tuple is usually immutable – marsibarsi Dec 02 '19 at 11:37