Michael Rennison
Michael Rennison

Reputation: 180

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
}

Upvotes: 4

Views: 518

Answers (3)

Maciej Sikora
Maciej Sikora

Reputation: 20132

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.

Upvotes: 1

iY1NQ
iY1NQ

Reputation: 2514

Here a solution if some type safety is needed:

interface Item<P1, P2> {
  parameter1: P1; 
  parameter2: P2; 
}

function myFunction<P1, P2>(items: Item<P1,P2>[]) {

  const data: [Item<P1, P2>['parameter1'], Item<P1, P2>['parameter2']][] = [];

  for (const item of items) {
    data.push([item.parameter1, item.parameter2])
  }

  return data; // returns [P1, P2][]

}

Playground Link

Upvotes: 0

StepUp
StepUp

Reputation: 38094

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.

Upvotes: 3

Related Questions