John Abraham
John Abraham

Reputation: 18811

Is it possible to destructure a property out of the object and assign it to a property on the constructor?

I'm using typescript and want to destructure properties out of an object. the problem is that I need to assign it to a property on the constructor of the class:

var someData = [{title: 'some title', desc: 'some desc'}];
var [{title}] = someData; // 'some title';

I want something more like:

var [{title :as this.title$}] = someData;

Is this possible in any shape or form?

Upvotes: 2

Views: 98

Answers (1)

Aluan Haddad
Aluan Haddad

Reputation: 31863

Yes, you can do this, but you need to remove the declarator (var) since you are destructuring into something that already exists. Also, the as is invalid syntax. Remove it.

[{title: this.title$}] = someData;

A complete example:

const someData = [
  { title: 'Destructuring' }
];

class A {
  title$: string;
  constructor() {
    [{ title: this.title$ }] = someData;
  }
}

TypeScript playground

Babel REPL

Via a Stack Snippet

const someData = [{
  title: 'Destructuring'
}];

class A {
  constructor() {
    [{title: this.title$}] = someData;
  }
}

console.log(new A());

Upvotes: 3

Related Questions