from Hacker News

Practical introduction to algebraic datatypes (ADTs) in TypeScript

by elnygren on 8/10/21, 12:10 PM with 21 comments

  • by lalaithion on 8/11/21, 2:52 PM

    I think this article makes the "sum" and "product" terms out to be very complicated, when in fact it's quite simple. If we have two enums

        enum Bool {
            True,
            False
        }
    
        enum Status {
            Waiting,
            Successful,
            Failed
        }
    
    We can combine them into a product type, like a tuple, or a sum type, like a union.

        type Product = (Bool, Status)
        type Sum = Bool | Status
    
    Now, we ask ourselves, what are the valid values of type Product?

        (True, Waiting)
        (True, Successful)
        (True, Failed)
        (False, Waiting)
        (False, Successful)
        (False, Failed)
    
    There are two Bool values, and three Status values, so there are 2×3=6 values for the product of Bool and Status. Now, what about the Sum type?

        True
        False
        Waiting
        Successful
        Failed
    
    We have 2+3=5 total values for the sum of Bool and Product.

    Now, obviously, this math doesn't quite work out for types with infinite values, like strings or bigints or arrays, but that's where the analogy comes from.

    If you extend this further, you can even figure out what an exponential type would be: the exponential type Bool^Status is a function that takes a Status as its argument and returns a Bool.

  • by benrbray on 8/11/21, 2:06 PM

    Definitely take a look at fp-ts [1]! It's mentioned at the end of the article, but I want to emphasize just how cool it is.

    [1] https://github.com/gcanti/fp-ts

  • by g_delgado14 on 8/11/21, 4:28 PM

    I spoke about this with Feross Aboukhadijeh last week at SpeakeasyJS:

    https://www.youtube.com/watch?v=QyunIFfKLIU

  • by inssein on 8/12/21, 3:31 AM

    ADTs like the one described here for remote data is a good start, but I haven’t yet found a good way to compose multiple pieces of data that is in potentially different states.

    We use another class based concept on top at work where you can compose multiple pieces of remote data together, but it really only works well for the happy path.

  • by ramesh31 on 8/11/21, 5:35 PM

    The switch case is still a bit redundant and inelegant, particularly considering how out of place switch case syntax feels in a Javascript codebase in general. Early returns are the way to go.