Skip to content

Instantly share code, notes, and snippets.

@matey-jack
Last active September 1, 2018 22:46
Show Gist options
  • Save matey-jack/e88a90e1a8c8ceec9c8e2fae7b880842 to your computer and use it in GitHub Desktop.
Save matey-jack/e88a90e1a8c8ceec9c8e2fae7b880842 to your computer and use it in GitHub Desktop.
Four ways to define functions in TypeScript
import "jest";
// C-style declared function with block body
function increment_block(i: number): number {
return i + 1;
}
// original JavaScript inline function
const increment_var_keyword = function(i: number): number {
return i + 1;
};
// fat-arrow inline function with block body
const increment_var_block = (i: number): number => {
const j = i + 1;
return j;
};
// fat-arrow inline function with expression body
const increment_var = (i: number): number => i + 1;
// The two fat-arrow variants can unfortunately collide when one wants to
// return an object literal. In that case, we need a pair of parenthesis to
// disambiguate.
const makeObject = () => ({ a: 15, b: 16 });
test("functions", () => {
expect(increment_block(1)).toBe(2);
expect(increment_var_keyword(1)).toBe(2);
expect(increment_var_block(1)).toBe(2);
expect(increment_var(1)).toBe(2);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment