TypeScript Return Type: void

Issue

In TypeScript (using in an Angular project), for a method that returns nothing (void), which of the following is the best practice?

onSelect(someNumber: number): void {

}

OR

onSelect(someNumber: number) {

}

I’ve seen it both ways in different examples and wasn’t sure if it is better to add the return type as void or to leave it blank?

Solution

It’s entirely personal preference whether you explicitly annotate a method’s return type or not, especially for a trivial type like void.

Reasons you might add : void:

  • Improves clarity – other devs don’t have to read the method body to see if it returns anything
  • Safer – if you e.g. move code from another function into this one that has a return expr; statement in it, TypeScript will flag this mistake

Reasons you might not:

  • Brevity – if it’s clear from context what the return type should be (e.g. getLength() is almost certainly returning number), then a return type annotation is slightly noisy
  • Flexibility – if you’re prototyping this code and aren’t sure yet what you want the return type to be, leaving it inferred lets you change it more easily

Answered By – Ryan Cavanaugh

Answer Checked By – Gilberto Lyons (AngularFixing Admin)

Leave a Reply

Your email address will not be published.