Different types of function declaration (foo () : void{} vs foo() {}) Angular2

So I was doing some tutorials on angular 2 when I found on their (angular.io) tutorial page this function declaration:

foo () : void {}

My question is… What’s the difference between that declaration and this?

foo() {}

I’ve figured out that the void is the return type but if you put for instance string instead of void both functions are able to return strings.

So whats the real difference and what is the best practice? ( I’m inclined to say the first one, just don’t know why).

And is that a Javascript, TypeScript, ES6 or even an Angular2 thing? Never seen that before.

7 thoughts on “Different types of function declaration (foo () : void{} vs foo() {}) Angular2”

  1. Type declarations are part of typescript and baked into the language. It’s usually best practice to include a type declaration wherever possible, including foo(): void, since it helps catch errors such as:

    foo(): void {
        return 'hello';

    You can see this example in practice in the TypeScript playground.

    The above shows an error in the typescript transpiler, and lets you know that you may be returning something when you did no expect to. In this case, it’s because there was no return expected, but one was provided.

    Ultimately it doesn’t make a difference to your code since both foo() {} and foo(): void {} will run the exact same way. In the end, it’s just a way of keeping track of your variables and ensuring they’re used properly. Here is an example of how TypeScript transpiles your TypeScript example into JavaScript.

    You can learn more about TypeScript here.


Leave a Comment