In Typescript (using in an Angular project) for a method that returns nothing (void), which of the below is 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 leave it blank?
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:
return expr; statement in it, TypeScript will flag this mistakeReasons you might not:
getLength() is almost certainly returning number), then a return type annotation is slightly noisyRemember the Rule : "void is the return type of a function/method that doesn’t explicitly return anything"
Whether your use "void" or not as return type in function/method, its automatically infer to "void" return type if there is no explicit return type
Another use-case which benefits from being explicit with 'void' return type IMO is one-line arrow functions.
// the second method has no body block, and implicitly returns the
// size of the internal array, which may not be the desired outcome
// explicitly stating a :void return type would flag the bottom one
// as an error
add = (v: string): => {this.list.push(v);};
addAndReturnLengthOfList = (v: string): => this.list.push(v);
'''