Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: Declare function that returns a nested array

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
}
like image 647
Michael Rennison Avatar asked Oct 15 '25 14:10

Michael Rennison


2 Answers

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.

like image 118
StepUp Avatar answered Oct 17 '25 05:10

StepUp


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.

like image 41
Maciej Sikora Avatar answered Oct 17 '25 06:10

Maciej Sikora