For example, I have a function:
functiom sum(a: number, b: number) { return a + b }
In the above function should I annotate the function's return type is number? Because I think both the developer and compiler can infer the function's result must be number type.
Also like httpClient.get method in Angular return Observable type, it already defined in its signature, should I explicitly declare it in my proxy consumer function?
function getPosts() {
return this.httpClient.get();
}
So my question is should I type everything? If not, when should I type it.
In a programming language that has both type inference and explicit manifest type annotations, you can think of the explicit manifest type annotations as the equivalent of double-entry bookkeeping in accounting: when you do everything right, it should never be needed, because the inferred type and the explicit type are always the same, but when you make a mistake, it helps you catch that mistake.
A good rule of thumb is:
Every public interface should be explicitly annotated.
Whether or not you annotate private interfaces is your choice.
Personally, I have a slightly more relaxed version:
Every public interface should be explicitly annotated, unless the type is blindingly obvious both from the name and the implementation.
So, for something like
export function toString() { return "Dummy user"; }
I feel it is okay to leave out the type annotation, but others disagree.
In your first example, it is probably fine to leave out the type annotation. Although in a language that overloads + for both addition and string concatenation, it is easy to accidentally write code that returns a string when you meant to return a number, so it might make sense to protect against that.
In your second example, I feel it should have a type annotation. Remember my personal rule:
Every public interface should be explicitly annotated, unless the type is blindingly obvious both from the name and the implementation.
I feel that the fact that a function named getPosts does not actually, you know, get the posts, but rather gets an Observable of posts is not sufficiently obvious.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With