Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define type of destructured argument in .map

Tags:

typescript

I have a destructured argument inside a map function:

array.map(([name, data], index:number) => (
    console.log(name + data)
))

How can I set name and data as name: string, data: object?

like image 389
João Pedro Avatar asked Jan 20 '21 12:01

João Pedro


2 Answers

The best way would be for array to have the correct type:

declare let array: Array<[string, object]>
array.map(([name, data], index:number) => (
    console.log(name + data)
))

You can also put the annotation on the destructuring expression:

declare let array: Array<any>
array.map(([name, data]: [string, object], index:number) => (
    console.log(name + data)
))
like image 175
Titian Cernicova-Dragomir Avatar answered Oct 02 '22 05:10

Titian Cernicova-Dragomir


Ideally, do it by making sure that array has a type, because then TypeScript will correctly infer the types of name and data. For example, here array has a type, so the types are inferred correctly:

const array = [
    ["example", {}],
];
const result = array.map(([name, data], index) => {
    console.log(name, data);
});

Playground link (note that you also don't need the type on index, since map's type says what it is)

As a second-best option, you can declare the type after the destructuring:

const result = array.map(([name, data]: [string, object], index:number) => {
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^^^
    console.log(name, data);
});

Playground link

like image 30
T.J. Crowder Avatar answered Oct 02 '22 06:10

T.J. Crowder