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?

1 answer

  • answered 2018-11-08 07:59 Titian Cernicova-Dragomir

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