TypeScript Version: 2.8.1, 2.9.0-dev.20180510
Search Terms:
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:
https://www.typescriptlang.org/play/index.html#src=const%20pickupNumbers%20%3D%20(a%3A%20any%5B%5D)%20%3D%3E%20(%0D%0A%20%20%20%20%2F%2F%20filter%20by%20numbers%0D%0A%20%20%20%20a.filter((x)%20%3D%3E%20(typeof%20x%20%3D%3D%3D%20'number'))%20as%20number%5B%5D%0D%0A)%3B%0D%0Aconsole.log(pickupNumbers(%5B0%2C%201%2C%202%2C%20'3'%2C%20'4'%2C%205%2C%20null%5D))%3B%0D%0A
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
TypeScript Version: 2.8.1, 2.9.0-dev.20180510
Search Terms:
Code
Expected behavior:
Array
[0, 1, 2, 5]will be loggedActual behavior:
undefinedwill be loggedPlayground Link:
https://www.typescriptlang.org/play/index.html#src=const%20pickupNumbers%20%3D%20(a%3A%20any%5B%5D)%20%3D%3E%20(%0D%0A%20%20%20%20%2F%2F%20filter%20by%20numbers%0D%0A%20%20%20%20a.filter((x)%20%3D%3E%20(typeof%20x%20%3D%3D%3D%20'number'))%20as%20number%5B%5D%0D%0A)%3B%0D%0Aconsole.log(pickupNumbers(%5B0%2C%201%2C%202%2C%20'3'%2C%20'4'%2C%205%2C%20null%5D))%3B%0D%0A
Details:
The above TS code will be compiled to the following (target: es5):
returnin the first line is treated as returning nothing, soundefinedwill be returned. The parentheses arounda.filter(...)are dropped when both comment and type assertion are written inside the parentheses.Workaround:
as number[]after the parentheses (or put<number[]>before the parentheses)a.filter(...)from TS code