News for hackers. Stuff that matters.
Re:TypeScript 4.1 by CraigJPerry on Friday November 20, 2020 @07:40AM (#25159860)
Can 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?

Re:TypeScript 4.1 by egeozcan on Friday November 20, 2020 @08:15AM (#25160136)
When 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.

Re:TypeScript 4.1 by mlnj on Friday November 20, 2020 @08:47AM (#25160389)
And beyond the isAuthenticated() / isAuthorized() call in the flow there only needs to be the use of AuthenticatedUser.
Re:TypeScript 4.1 by CraigJPerry on Friday November 20, 2020 @09:46AM (#25160879)
Wait

    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?
Re:TypeScript 4.1 by egeozcan on Friday November 20, 2020 @10:18AM (#25161235)
If 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.

Re:TypeScript 4.1 by filoeleven on Friday November 20, 2020 @01:21PM (#25163238)
I 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.