I'm currently trying to reduce a string into number[], but I'm new to typescript and simply couldn't figure out how to type my code so that the typescript compiler would stop complaining...
What I'm trying to do:
matString.split(/[\n ]/).reduce((acc, cur, index) => acc[index] = Number(cur));
So far, I have tried typing it like this, but it just won't work :(
matString.split(/[\n ]/).reduce((acc: Array<number>, cur, index) => acc[index] = Number(cur)) as Array<number>;
Just for context, this code is receiving a matrix in the format of a string and I want to convert it down to an array so that I can work with it. I have already encountered this issue under different circumstances and had to work around it, but this time I would like to understand how to fix it.
Also, if it does help explain my issue better, here's a picture of my code followed by the compiler's error: code image with error
While it's possible, it'd be far easier to avoid .reduce and just map the split string to Number, no explicit typing necessary:
const result = matString
.split(/[\n ]/)
.map(Number);
If you had to go the .reduce route, use generics to indicate the accumulator type, and remember to return the accumulator at the end of the callback:
const result = matString.split(/[\n ]/).reduce<Array<number>>((acc, cur, index) => {
acc[index] = Number(cur);
return acc;
}, []);
If the input is composed of a string that contains numeric characters, it might be better to match those characters, instead of splitting on newlines and spaces:
const result = matString
.match(/\d+(?:\.\d+)?/g) // assuming there will always be at least one match
.map(Number);