Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Types in object destructuring

This

const { foo: IFoo[] } = bar; 

and this

const { foo: Array<IFoo> } = bar; 

will reasonably cause an error.

And this

const { foo: TFoo } = bar; 

will just destructure TFoo property.

How can types be specified for destructured object properties?

like image 984
Estus Flask Avatar asked Sep 24 '16 05:09

Estus Flask


People also ask

What is the object Destructuring?

JavaScript Object Destructuring is the syntax for extracting values from an object property and assigning them to a variable. The destructuring is also possible for JavaScript Arrays. By default, the object key name becomes the variable that holds the respective value.

How do you Destructure an object in TypeScript?

TypeScript casting a destructured object typeconst {firstname: string, age: number} = user; But this assigns the firstname variable to be string and the age variable to be called number . And when we introduce two of the same type, we are hit with an error since we are redefining a variable.

What is object and array Destructuring?

Destructuring is the act of unpacking elements in an array or object. Destructuring not only allow us to unpack elements, it also gives you the power to manipulate and switch elements you unpacked depending on the type of operation you want to perform. Let's see how destructuring works in arrays and objects now.

Can you Destructure an object?

Destructuring is a JavaScript expression that allows us to extract data from arrays, objects, and maps and set them into new, distinct variables. Destructuring allows us to extract multiple properties, or items, from an array​ at a time.


1 Answers

It turns out it's possible to specify the type after : for the whole destructuring pattern:

const {foo}: {foo: IFoo[]} = bar; 

Which in reality is not any better than plain old

const foo: IFoo[] = bar.foo; 
like image 111
artem Avatar answered Sep 24 '22 22:09

artem