简体   繁体   中英

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;

The correct syntax is:

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

Reference

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM