3 ms·
And with TypeScript I get notified that I forgot something and it shows me exactly where.
by mlnj 6y ago
And with TypeScript I get notified that I forgot something and it shows me exactly where.
- CraigJPerry 6y agoCan types solve that problem? ... // if(isAuthorised(user)) { doSomethingWithThing(thing); // } ... How would typing detect the missing authorisation check in the program flow? Surely this is a case where testing is the correct tool to use?
- deleted 6y ago[deleted]
- egeozcan 6y agoWhen User is a type of: Guest | AuthenticatedUser and isAuthorised is a type guard like: function isAuthorised(user: User): user is AuthenticatedUser { return user.isLoggedIn /* or whatever */} as long as doSomethingWithThing accepts just AuthenticatedUser, yes it can be caught. You can also use discriminated unions with implicit type refining from TS without type guards.
- mlnj 6y agoAnd beyond the isAuthenticated() / isAuthorized() call in the flow there only needs to be the use of AuthenticatedUser.
- CraigJPerry 6y agoWait doSomethingWithThing(thing) Doesn't know about user, why does it need to be polluted with the concept of an AuthenticatedUser type which it does nothing with?
- egeozcan 6y agoIf that action has a dependency to a user (an authenticated user or a user with a specific permission), it's a good practice to establish this dependency also in the code level. "doSomethingWithThing" probably does IO, and the changes need to be traced back somehow (e.g. a ModifiedBy column in a DB). You can solve this context problem through a DI container, or by direct parameter passing, but whatever you do, there will be a layer which can expose the requirements as types. I'm not a know-it-all who'll dictate how you need to structure your program on HN, so what I stated above is just me thinking out loud, but let's say it's up to the programmer to make everything safe-r with the tools available, be it runtime checks or the type system.
- filoeleven 6y agoI think GP may have meant to say that whatever code is _calling_ doSomethingWithThing() there should only accept AuthenticatedUser. It hoists your original check to the calling function’s signature. I agree with you that this doesn’t really solve the flow problem though: someone still has to decide that the function only receives AuthenticatedUser and not Guest. That’s not a net gain, it’s just shuffling responsibility around, and it could be a net loss if the calling function does “a bunch of identical things for any user type” and then “this one extra thing if user is authenticated.” But I’m not a Typescript user or a big fan of complex type systems either.