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?
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)
))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With