Hacker News new | past | comments | ask | show | jobs | submit login

100% agree with this. If you're using redux the boilerplate of Typescript is huge. To do that all that work and still have the compiler miss problems at the state level deemed Typescript pointless to me.



Not sure which specific issues you encountered, but I had issues with defining actions and using their types in a union to the reducer.

There is a nice little library [1] that fixes this issue.

So a general redux setup looks as follows:

    const FETCH_USERS_BEGIN = "@@FOO/FETCH_USERS_BEGIN"
    const FETCH_USERS_SUCCESS = "@@FOO/FETCH_USERS_SUCCESS"
    const FETCH_USERS_ERROR = "@@FOO/FETCH_USERS_ERROR"

    const fetchUsersBegin = () => action(FETCH_USERS_BEGIN)
    const fetchUsersSuccess = (users: IUser[]) => action(FETCH_USERS_SUCCESS, users)
    const fetchUsersError = () => action(FETCH_USERS_ERROR)

    type IActions =
      | ReturnType<typeof fetchUsersBegin>
      | ReturnType<typeof fetchUsersSuccess>
      | ReturnType<typeof fetchUsersError>


    interface IUser {
      id: number
      name: string
    }

    interface IState {
      readonly isLoading: boolean
      readonly isErrorLoading: boolean
      readonly allIds: number[]
      readonly byId: {
        readonly [key: number]: IUser
      }
    }

    const defaultState = {
      isLoading: false,
      isErrorLoading: false,
      allIds: [],
      byId: {}
    }

    const reducer = (state: IState = defaultState, action: IActions) => {
      // narrowing on types
      switch (action.type) {
        case FETCH_USERS_BEGIN:
          return { ...state, isLoading: true, isErrorLoading: false }
        case FETCH_USERS_SUCCESS:
          return {
            ...state,
            byId: action.payload.reduce(
              (acc, u) => ({ ...acc, [u.id]: u }),
              {}
            ),
            allIds: action.payload.map(u => u.id),
            isLoading: false,
            isErrorLoading: false
          }
        case FETCH_USERS_ERROR:
          return {
            ...state,
            isLoading: false,
            isErrorLoading: true
          }
        default:
          return state
      }
    }



[1]: https://github.com/piotrwitek/typesafe-actions#1-classic-js-...


I've found myself preferring type guards for checking action type, since it avoids you having to have keep one big `Actions` union around that takes X amount of lines and really doesn't serve any other purpose.


Is Redux a TS native library? Angular has typing issues of its own, e.g. Forms are typed with 'any', no easy access to certain HTMLElements' properties, etc., but the rest is okay. (Meaning hard to do bad things without early warning/failure during compilation.)




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: