Clem
Clem

Reputation: 11824

Typescript named object destructuring

Is it possible to destruct object with custom variable names?

TypeScript:

const { top } = { top: 1000 };

JavaScript:

var top = { top: 1000 }.top;

But I want something like shown bellow(does not work).

TypeScript:

const { top as elementTop } = { top: 1000 };

JavaScript:

var elementTop = { top: 1000 }.top;

Upvotes: 6

Views: 6006

Answers (2)

Aditya Singh
Aditya Singh

Reputation: 16690

This is an ES6 de-structuring when you need to assign to new variable names:

var o = {p: 42, q: true};

var {p: foo, q: bar} = o;

In your example, it will be:

const { top: elementTop } = { top: 1000 }; 

For additional details: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

Upvotes: 3

David Sherret
David Sherret

Reputation: 106790

The correct syntax is:

const { top: elementTop } = { top: 1000 };

Reference

Upvotes: 8

Related Questions