News for hackers. Stuff that matters.
Re:Simpler UI Logic With Finite State Machines by bcherny on Monday December 23, 2019 @01:14PM (#21865654)
If your code is fully typed, you don't need the default, since you know at compile time that you've handled your cases (Playground link: [0]):

    type Props =
      | { type: 'a', a: number }
      | { type: 'b', b: string }

    function f(props: Props): number {
      switch (props.type) {
        case 'a': return 1
        case 'b': return 2
      }
    }
Unfortunately you're right that this breaks when using `if` instead of `switch` (unless you have a default return at the end of your function, or replace one of your `if`s with an `else`; Playground link: [1]):

    type Props =
      | { type: 'a', a: number }
      | { type: 'b', b: string }

    // Error TS2366: Function lacks ending return statement and return
    // type does not include 'undefined'.
    function f(props: Props): number {
      if (props.type === 'a') {
        return 3
      }
      if (props.type === 'b') {
        return 4
      }
    }
This second case is a bug in TSC, and is tracked in https://github.com/microsoft/TypeScript/issues/18319.

[0] https://www.typescriptlang.org/play/#code/AQ4FwTwBwU2AFATgey...

[1] https://www.typescriptlang.org/play/#code/AQ4FwTwBwU2AFATgey...

There are no comments on this comment yet.