I'm declaring a function in typescript that returns a nested array, but i'm unsure on how to declare the return type and declare the array that gets returned. Can anyone help? Here's what I have
myFunction(items: any): [] {
const data = [];
for (const item of items) {
data.push([item.parameter1, item.parameter2])
}
return data; // IDE throws error here
}
You can use myFunction(): any[][]
:
An example:
myFunction(): any[][] {
let data = [,];
data = [[1], [2], [3]];
console.log(data);
return data;
}
A stackblitz example can be seen here.
As we work with static type system, the more correct way would be to specify something more than any
. Consider such type safe version:
type Item = {
parameter1: any; // here better some type
parameter2: any; // here better some type
}
type ParametersTupleArr = [Item['parameter1'], Item['parameter2']][]; // return type
function myFunction(items: Item[]): ParametersTupleArr {
const data = [] as ParametersTupleArr;
for (const item of items) {
data.push([item.parameter1, item.parameter2])
}
return data;
}
Type [Item['parameter1'], Item['parameter2']][]
says that we will output array of 2-element tuples with types of parameters of Item
.
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