when TypeScript infers the variable type correctly, should I set the type explicitly? for exa:
const add = (a: number, b: number) => a + b;
const result = add(2, 3);
// or should I explicitly set return value type?
const add = (a: number, b: number): number => a + b;
const result = add(2, 3);
I know type inference has many cases. If this one is not a bad practice, I would like to know if there's any case in which explicit types are better.
I agree the answer to your question of when to add explicit types if the type can already be inferred is to some degree a manner of opinion, since the explicit types are not required in these cases. However, there are some advantages and disadvantages to adding explicit types (when not required):
Disadvantages:
Advantages:
IMO explicit types are superfluous for simple functions (e.g. trivial lambda functions with a single return value) but are well worth the extra effort for complex functions (e.g. functions with multiple return statements). Since functions tend to become more complex over type, I err on the side of adding explicit return types to functions.