3
nururururu
318d

"You don't need to put a type annotation here, the type will be inferred by the compiler"

"We don't need to mark this function as async, since we are already returning a promise but not awaiting it yet within this method"

TypeScript codebase. Am I wrong to prefer that things be explicit rather than implicit? Sounds a bit tryhard to try and make things implicit, but maybe the async really changes behavior in the second case? I don't think so, and I prefer to mark an asynchronous operation as such, but I'm still doubtful; that's why I humbly ask you all what makes more sense here.

Comments
  • 6
    My rule is. Unless it's obvious to a human reader, I wouldn't omit the annotation.

    Basically the same point but replace compiler by "another human"
  • 1
    Since types in Typescript, I prefer having it inferred precisely rather than relying the good will of every other devs not ending up with a too vague generic interface.
  • 1
    And since I am here

    Please name your generic types other things than T, U or V

    And Please please please 🙏 don’t make .md for everything, use TSdoc
  • 3
    The async rule keyword makes no sense to me.

    Marking a function async is nothing more than syntactic sugar for: this function will always return a promise. Nothing more nothing less.

    async fn() => 3

    You'll know you get a promise (even though it instantly resolves).

    Furthermore, the async declaration allows the `await` keyword. Yet you don't have to use await if you don't need it.

    While it is true to use `await` with caution and only when you need it, there still is a benefit of ease of use of declaring all functions that may interact with Promises or return them as async.

    If you don't mark you function as async and still work with promises you might get stuck in callback hell and being unsure what exactly your function may return, and I worked with libraries that sometimes returned a discrete value, and other times some promise. That's madness.
  • 1
    Apart from reducing cognitive load for fellow humans, the annotations alse ensure that the compiler tells you if it disagrees with the type annotation. If you annotate by default, all those tiny type assertions together make type confusion bugs much more likely to get fixed before the first execution.
  • 1
    welcome to the warrior world VS the BS hippies making tech
  • 1
    @Oktokolo Yes, this is why I prefer to annotate even when not needed, so the compiler and the language server can tell me things like "hold on a second, this operation could return undefined or perhaps null, not just the type you've specified".
Add Comment