Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSDoc typings for typescript for JavaScript reducer accumulator

I am trying to type the accumulator in a JavaScript reducer using JSDocs but cannot work out how to do this.

I've tried typing it inline at initialization but that didn't work. Any hints or ideas? Here's the sample code. It's complaining about param passed to arr.push():

/**
* @type {Array<String>}
*/
const arr = ['one', 'two', 'three'];

/**
 * @type {Array<Array>}
 */
const result = arr.reduce((acc, item) => {
   if(item.length % 3 === 0) {
     // [ts] Argument of type '(string | number)[]' is not assignable to
     // parameter of type 'never'.
     acc.push([item, item.length]);
   }
   return acc;
}, []);

Here's the GitHub repo which has the tsconfig.json file in the root of the project for the tsc settings: https://github.com/guyellis/typescript-as-a-linter

And here's the file in that repo from which I took the code above: https://github.com/guyellis/typescript-as-a-linter/blob/master/lib/reducer.js

like image 939
Guy Avatar asked Oct 16 '22 13:10

Guy


1 Answers

The empty array you are passing as the initial state gets the type never[]. See this thread for more background. To avoid that, you can put it in a constant and give the constant a type:

/**
* @type {Array<String>}
*/
const arr = ['one', 'two', 'three'];

/** @type {Array<[string, number]>} */
const init = [];

/**
 * @type {Array<[string, number]>}
 */
const result = arr.reduce((acc, item) => {
   acc.push([item, item.length]);
   return acc;
}, init);
like image 70
Matt McCutchen Avatar answered Oct 21 '22 05:10

Matt McCutchen