FormidableLabs / redux-little-router

A tiny router for Redux that lets the URL do the talking.
MIT License
1.04k stars 113 forks source link

Improve TS definitions #270

Closed NeoLegends closed 6 years ago

NeoLegends commented 6 years ago

First of all, thanks so much for finally getting TS definitions in here! Great work!

However, we can still optimize them a little. First, I strongly typed (or stringly typed, hehe) the actions' type property. This way, you can build up sum types from all the actions you use in your applications, which TS can then narrow inside your reducers, which results in that you have strongly typed action payloads ✌️. Take a look at the following example:

import { RouterActions, LOCATION_CHANGED, UNBLOCK } from 'redux-little-router';

function reducer(state: State = {}, action: RouterActions): State {
  switch(action.type) {
    case LOCATION_CHANGED:
      // TS knows that `action.payload` _must_ be `Location` now
      console.log(`Hey, this compiles! ${action.payload.pathname}`);
      return state;
    case UNBLOCK:
      // TS knows that `action.payload` doesn't exist
      console.log(`Hey, this doesn't compile! ${action.payload.pathname}`);
      return state;
    default:
      return state;
  }
}

With the second commit, I removed actions that weren't exported from the main module (locationDidChange) and added missing ones in (block, unblock).

Would love to get this through quickly so that people can benefit from it. :)

codecov[bot] commented 6 years ago

Codecov Report

Merging #270 into master will not change coverage. The diff coverage is n/a.

Impacted file tree graph

@@           Coverage Diff           @@
##           master     #270   +/-   ##
=======================================
  Coverage   98.61%   98.61%           
=======================================
  Files          28       28           
  Lines         362      362           
=======================================
  Hits          357      357           
  Misses          5        5

Continue to review full report at Codecov.

Legend - Click here to learn more Δ = absolute <relative> (impact), ø = not affected, ? = missing data Powered by Codecov. Last update c2ee3c7...fb7f8a8. Read the comment docs.

NeoLegends commented 6 years ago

@parkerziegler Done.

NeoLegends commented 6 years ago

🎉