with reference todo app of sitepoint tutorial If I remove the return type TodoDataService
from addTodo
and deleteTodoById
the app functions the same. Then what is the significance of using return type as TodoDataService
in addTodo
and deleteTodoById

- 759
- 7
- 17
-
Best practice is to type _everything_. Making sure your accessor is expecting the same output as your return value simply prevents errors later on and allows most IDE to catch errors before compilation. – Z. Bagley Sep 04 '17 at 18:44
1 Answers
Taken from the comments, there are two questions here:
- Why are the
addTodo
anddeleteTodoById
functions annotated with a return type ofTodoDataService
, given that Typescript is also happy if they are not provided?
TypeScript is rather clever. It can infer that the return type is TodoDataService
, given that the code for both functions returns a TodoDataService
instance. If you and I were to read the code, we could come to the same conclusion. However, explicitly annotating the return type is our way of telling TypeScript that the return type must be TodoDataService
.
So, in the case where we do not have the annotation, it would be perfectly fine to remove the return this
line. Note that TypeScript would now infer that the return type is void
, as we're no longer returning a value.
When using the explicit annotation, if we remove the return this
line, TypeScript will complain. In this case, we've told it that a TodoDataService
must be returned, yet we have failed to return anything at all.
- Why do both the
addTodo
anddeleteTodoById
functions belonging toTodoDataService
return theTodoDataService
itself?
This is an example of Method Chaining. The basic idea here is to make the code look a little bit cleaner. For example, if you wanted to add two Todo
s and remove one, you could write:
todoDataService.addTodo(...);
todoDataService.addTodo(...);
todoDataService.deleteTodoById(...);
Using method chaining (i.e. by returning the service from the functions), you could instead write:
todoDataService
.addTodo(...)
.addTodo(...);
.deleteTodoById(...);
In the tutorial you've referenced, there is no reason for the return this
line. Although I haven't had chance to read through the full details of the article, I cannot see anywhere that method chaining is actually used with TodoDataService
.

- 84,915
- 16
- 214
- 203