Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 374
Rafael Chaves Avatar asked Mar 07 '17 17:03

Rafael Chaves


1 Answers

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.

like image 100
Adam Avatar answered Sep 21 '22 03:09

Adam