I am working on this function that takes an array of distance meters is the default, and converts is back to feet and miles, the problems is I am getting this error I stated that option must return an array of numbers any idea where is this syntax error. Type 'void[]' is not assignable to type 'number[]'.
const option = () => {
let arr = [200, 400, 800, 1000, 1, 2, 3, 4, 5];
return arr.map((x, i) => {
i <= 3 ? x * 3.281 : x / 1.609;
});
}
console.log(option());
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
You are both missing a return
and not: when using an arrow function, if your function body is a single statement, you can omit both the {}
and the return
statement:
const option = () => {
let arr = [200, 400, 800, 1000, 1, 2, 3, 4, 5];
return arr.map((x, i) => i <= 3 ? x * 3.281 : x / 1.609);
}
console.log(option());
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Incidentally, this also lets you do things like:
const materials = [
'Hydrogen',
'Helium',
'Lithium',
'Beryllium'
];
console.log(materials.map(material => material.length));
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
There's missing a return statement inside the arrow function passed to map
return arr.map((x, i) => {
return i <= 3 ? x * 3.281 : x / 1.609;
});
to return a value without writing return, you can do like this
return arr.map((x, i) => (
i <= 3 ? x * 3.281 : x / 1.609;
));
replace { with (
CodePudding user response:
What you need to return the value once it is passes through the map.
const option = (): number[] => {
const arr = [200, 400, 800, 1000, 1, 2, 3, 4, 5];
arr.map((x, i) => {
return i <= 3 ? x * 3.281 : x / 1.609;
});
return arr;
}