Closed
Description
TypeScript Version: 2.8.1, 2.9.0-dev.20180510
Search Terms:
- arrow
- return undefined
Code
const pickupNumbers = (a: any[]) => (
// filter by numbers
a.filter((x) => (typeof x === 'number')) as number[]
);
console.log(pickupNumbers([0, 1, 2, '3', '4', 5, null]));
Expected behavior:
Array [0, 1, 2, 5]
will be logged
Actual behavior:
undefined
will be logged
Playground Link:
Details:
The above TS code will be compiled to the following (target: es5):
var pickupNumbers = function (a) { return
// filter by numbers
a.filter(function (x) { return (typeof x === 'number'); }); };
console.log(pickupNumbers([0, 1, 2, '3', '4', 5, null]));
return
in the first line is treated as returning nothing, so undefined
will be returned. The parentheses around a.filter(...)
are dropped when both comment and type assertion are written inside the parentheses.
Workaround:
- Remove comment before compiling
- Remove type assertion, or move
as number[]
after the parentheses (or put<number[]>
before the parentheses) - Use block statement instead of expression
- (In this case) remove the parentheses around
a.filter(...)
from TS code