Search code examples
angulartypescriptecmascript-6angular5destructuring

angular 4 typescript destructuring doesn't work as expected


Desctruturing doesn't work when using this. syntax

 {this.firstName, this.lastName} = this.data;

this.data has value of

{firstName: 'joe', lastName: 'smith'}

but after assigning the value of this.firstName and this.lastName is still null


Solution

  • Try the following to achieve destructuring without declaration:

    ({firstName: this.firstName, lastName: this.lastName} = this.data);
    

    From MDN:

    The round braces ( ... ) around the assignment statement is required syntax when using object literal destructuring assignment without a declaration.

    The TypeScript compiler will also complain without the wrapping parenthesis.

    Here is example in action.

    Hopefully that helps!