News for hackers. Stuff that matters.
Re:If TypeScript is so great, how come all notable ReactJS p... by saguiar on Tuesday September 20, 2016 @01:25PM (#12541231)
I've been using discriminated unions on TS 2 to do this, and works quite well.

Example:

  const INCREMENT: "increment" = "increment";
  const DECREMENT: "decrement" = "decrement";

  interface Increment {
      type: typeof INCREMENT;
      payload: {
          inc: number;
      };
  }

   interface Decrement {
      type: typeof DECREMENT;
      payload: {
          dec: number;
      };
  }

  interface State { 
      count: number; 
  }

  type Actions = Increment | Decrement;

  function reducer(state: State, action: Actions) {
     switch (action.type) {
        case INCREMENT: {
             const { inc } = action.payload;
             return { count: state.count + inc };
         }
         case DECREMENT: {
             const { dec } = action.payload;
             return { count: state.count + dec };
         }
         default:
             return state;
     }
  }
Once TS figures out the action type is INCREMENT, it can infer the type of the payload. You don't need the Actions type either, you can just receive action: Increment | Decrement.
Re:If TypeScript is so great, how come all notable ReactJS p... by mpawelski on Wednesday September 21, 2016 @04:05AM (#12546269)
Yes, I'm doing basically the same (define constant a as literal type, then use "typeof" operator to define action type, and then create alias for all Actions using union type).

That's one of the reasons why I miss possibility to tell what is the type of the object that function returns. So I could do something like this (hypothetical syntax)

    const INCREMENT: "increment" = "increment";
    const DECREMENT: "decrement" = "decrement";

    function increment(inc: number) {
        return {
            type: INCREMENT,
            inc
        };
    }

    function decrement(dec: number) {
        return {
            type: DECREMENT,
            dec
        };
    }

    type Actions =
        returntypeof increment
        | returntypeof decrement;
So I won't need to write action type when I have action creator method. I hope that in future Typescript devs will add some feature to allow this kind of pattern.