angular typescript - when to specify types of parameters

Viewed 807

When going over angular 2 tutorials, I can see that in certain places the type of class properties is specified, for example name: string;, and in some places it is omitted. Same goes for function return types. This makes it unclear to me what is the best practice in this regard. If you choose to omit the type, don't you lose one of the biggest benefits of typescript?

3 Answers

TypeScript can infer type of a parameter from assignment, but at times if it cannot infer type it uses any.

Using TypeScript compiler flag noImplicitAny can alter this behavior. When the noImplicitAny flag is true and the TypeScript compiler cannot infer the type, it still generates the JavaScript files, but it also reports an error.

But you can still explicitly set any on a type if required.

Type checking indeed had its advantage and I would always recommend to use it. The good thing about TypeScript is, unlike other language you can be very succinct with types. We can write

doWork(work:{details:string})

Which allows strict type checking without the need for come up with a new type declaration altogether, albeit this cannot be shared.

I think your question might end up being flagged as too broad or opinion based, however, I would strongly suggest using types whenever possible. That is one of the benefits of typescript. Catching errors early, at compile type, versus spending hours debugging just to find out something silly like a typo.

One possible explanation to why the lack of types on their documentation could be to keep simpler, less scary for non-typescript folks coming from AngularJs.

For more info on the benefits of typescript please check this post: https://stackoverflow.com/a/12694578/222328

Lastly I'd suggest taking a look at the angular style guide: https://angular.io/guide/styleguide

I think, it's more readable to specify type of the paremeter or the type of function's return.

And, for some IDE like Intellij, it's good too! Because, it parses the code and during the auto completion, it displays thoses types

Related