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

1148 views arrays
2

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?

answered question

1 Answer

13

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[][]

posted this

Have an answer?

JD

Please login first before posting an answer.