Skip to content

Instantly share code, notes, and snippets.

@baetheus
Last active January 23, 2018 23:08
Show Gist options
  • Select an option

  • Save baetheus/7d18511c46d425e2b633ac4cdc4f9f82 to your computer and use it in GitHub Desktop.

Select an option

Save baetheus/7d18511c46d425e2b633ac4cdc4f9f82 to your computer and use it in GitHub Desktop.
POC for reducing action boilerplate
// This is where the magic is
export class PayloadAction<T, P = undefined> {
readonly type: T;
constructor(public readonly payload: P) {};
}
// These would be existing interfaces
export interface SomePayload {
stuff: string;
things: number[];
}
export interface OtherPayload {
blah: string;
}
// Action File Start (This is the resulting action creation code)
export enum actionTypes {
one = 'one',
two = 'two',
three = 'three',
}
export class OneAction extends PayloadAction<actionTypes.one, SomePayload> {};
export class TwoAction extends PayloadAction<actionTypes.two, OtherPayload> {};
export class ThreeAction extends PayloadAction<actionTypes.three> {}; // No payload on this action
export type Actions = OneAction | TwoAction | ThreeAction;
// Action File End
// Creating new actions works the same as before!
const a = new OneAction({stuff: 'a', things: []});
const b = new TwoAction({blah: 'b'});
// Type Narrowing in reducers also works the same as before!
function someReducer(action: Actions) {
switch (action.type) {
case actionTypes.one:
return console.log('Got one action', action.payload.stuff);
case actionTypes.two:
return console.log('Got one action', action.payload.blah);
case actionTypes.three:
return console.log('Got three action', action.payload);
default:
console.log('Got default');
}
}
@baetheus
Copy link
Author

This fails because the enum in the generic statement never initializes the class type property. ;_;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment