J. Hesters
J. Hesters

Reputation: 14768

How to tell TypeScript that I'm returning an array of arrays of the input type?

I have a function that chunks arrays:

const chunkArray = (inputArray: any[], chunks: number) => {
  const chunkedArray = [];
  let i = 0;
  const n = inputArray.length;

  while (i < n) {
    chunkedArray.push(inputArray.slice(i, (i += chunks)));
  }

  return chunkedArray;
};

export default chunkArray;

I would like my linter to know for a given input array, what the output array looks like. For example for

const chunkedArrays = chunkArray([1, 2, 3, 4, 5], 2); // [[1, 2], [3, 4], [5]]

my linter should now, that chunkedArrays is an array of arrays of numbers. Currently it says it's an array of arrays of any.

How can I achieve that?

Upvotes: 0

Views: 1312

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249506

You need to add a generic type parameter to your function. The type parameter will capture the actual type of the elements in the input array and then you can use this generic type to specify how it relates to your result:

const chunkArray = <T>(inputArray: T[], chunks: number) => {
    const chunkedArray: T[][] = []; // use T as the type for chunkedArray
    let i = 0;
    const n = inputArray.length;

    while (i < n) {
        chunkedArray.push(inputArray.slice(i, (i += chunks)));
    }

    return chunkedArray;
};

const chunkedArrays = chunkArray([1, 2, 3, 4, 5], 2); // number[][]
const chunkedArraysString = chunkArray(["1", "2", "3", "4", "5"], 2); // string[][]

Upvotes: 3

Related Questions