Skip to content

Arrow function with comment and type assertion will be compiled into unexpected ES5 script #24021

Closed
@jet2jet

Description

@jet2jet

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:

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:

  1. Remove comment before compiling
  2. Remove type assertion, or move as number[] after the parentheses (or put <number[]> before the parentheses)
  3. Use block statement instead of expression
  4. (In this case) remove the parentheses around a.filter(...) from TS code

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFixedA PR has been merged for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions