← Back
typescript

My (current) way to write a function definition in TS

I think I've been writing typescript regularly for over two years now, and my style has changed over time.

Specifically, regarding to function definitions, there are two changes that I am very happy with:

1. Prefer a single-object parameter than having a list of parameters. #

This is similar to keyword arguments in ruby. Essentially, it has two advantages: It's easier to read and understand (because the parameters are named... no need to look at the function signature to know what they mean) Adding or parameters doesn't introduce break changes to the code

I try to follow this rule on lof of functions, but I enforce it when the number of arguments are bigger than 3.

2. Prefer inline type definitions #

Instead of having a type defined outside the function, include the type definition inside the function declaration. The advantage of this is that the function is self-contained: it has no dependencies -to the external type(s)- and can be moved freely.

Example #

Because of this, for people coming outside typescript world, the syntax could be a little bit daunting: Function definition

So let's dive in: Divide and conquer

  1. Parameters: As a parameter, we pass a single object. But we use destructuring to get the actual values from the object (notice the outer {}). This way it "looks like" actual parameters.
  2. Parameters type: here we define the shape of the parameter object. It looks like a lot of duplication (in some way, it is) but here we define the types of each value of the object. Optional parameters are marked like with a ? (like vcGroupId in this example). Like any other type definition, this is removed from the resulting code after compilation
  3. Return type: again is a type (removed from compilation). In this case we're indicating that we're returning a Promise to an object that, in turn, contains two keys/values.

I know it's hard to get this kind of syntax at the beginning, but after several moths of usage I'm really happy with it. I encourage to give it a try.

By the way, the above screenshot is taken from a class method. For this reason, the function keyword is not present.