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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With