Thursday, September 17, 2015

TypeScript Lambda Gotcha

I came across a little gotcha today in TypeScript that I hadn't thought about before (but should have known better). When you use lambdas syntax, if you don't wrap it in curly braces it returns the result of the expression. In most cases this is probably fine, but not if the caller of your function is looking for a return type. I was using the LoDash _.each() function which allows you to pass back false if you want to break the loop. And unfortunately I was setting a boolean variable in the lambda without using curly braces. So every time I set the variable to false it broke the loop and I got bugs :-(.

For example, here I'm not using braces around my lambda expression, so whenever item.condition is not 1 it breaks the loop.

_.each(items, (item) => item.visible = (item.condition === 1));

This compiles down to:

_.each(items, function(item) { return item.visible = (item.condition === 1); });
See how it inserted a return statement? That's not we wanted!

By simply adding curly braces the return is removed and you get the correct behavior.

_.each(items, (item) => { item.visible = (item.condition === 1); });
It compiles to:

_.each(items, function(item) { item.visible = (item.condition === 1); });

So maybe I should start using braces when I don't want to explicitly return a value. But it looks so much cleaner the other way when you just want to do a simple one-liner. So we'll see...

No comments:

Post a Comment