1. 8

  2. 2

    Thanks, the part about conditional types helped me understand how that feature works.

    If you were building state machines for an application would you actually follow the approach demonstrated in the blog post, or use a library? (xstate comes to mind)

    1. 2

      Glad you enjoyed it!

      I hadn’t heard of xstate but I’ve thought about building something similar in TypeScript. I currently use a type like the Resource type described in the blog post in production. For fun, I have tried to do something with Redux where new states are dependent upon the old state and the action passed in, but I’ve run up against limitations in TypeScript itself such as: https://github.com/microsoft/TypeScript/issues/24929

      I’m hopeful things will continue to improve and these sorts of issues will get ironed out in the future given all the momentum TypeScript has going for it.

      I do feel like with my current stack that I’ve been using (React/Redux/redux-loop + TypeScript) is converging upon a nice Elm-like frontend architecture with a decent amount of type safety and a huge ecosystem to draw from. I plan on continuing to experiment and follow TypeScript’s development to see how that stack could be made even more ironclad which could open up some cool possibilities in the future.

    2. 2

      Great read.

      We usually have a type called State defined at the top of each component. For example:

      type State = {
          state: "searching",
      } | {
          state: "failed",
          error: str | null,
      } | { 
          state: "results_found",
          results: []any,
      1. 2

        This is closer to how I do it. But I split out the definition of each variant, and define helper functions to construct the variant from the data. The result is close to algebraic data types, except for the lack of exhauativeness checking. I’ve seen some articles that try to use the type system to get exhauativeness checking, but I haven’t had any luck with it so far.

        1. 1

          We implement an “assert never” function to help with exhauativeness checking with this type of state definition and it’s been working pretty well (catching missing cases, alerting when unknown values are used).

          Found this similar project on GitHub:


          1. 2

            Yeah, that’s what I tried, but I think it only works if you’re returning from all the branches, which did not apply for me.

      2. 1

        I could have sworn I read (and quite enjoyed!) this article a month or so ago.

        1. 1

          for folks that are using Flow (rather than typescript), this article covers somewhat simpler use case of union types