|
| 1 | +// Credits for the type detection technique: http://www.bluewire-technologies.com/2015/redux-actions-for-typescript/ |
| 2 | +import * as React from 'react'; |
| 3 | +import { Dispatch } from 'redux'; |
| 4 | +import './ObjectAssignPolyfill'; |
| 5 | + |
| 6 | +export interface ActionClass<T extends Action> { |
| 7 | + prototype: T; |
| 8 | +} |
| 9 | + |
| 10 | +export function typeName(name: string) { |
| 11 | + return function<T extends Action>(actionClass: ActionClass<T>) { |
| 12 | + // Although we could determine the type name using actionClass.prototype.constructor.name, |
| 13 | + // it's dangerous to do that because minifiers may interfere with it, and then serialized state |
| 14 | + // might not have the expected meaning after a recompile. So we explicitly ask for a name string. |
| 15 | + actionClass.prototype.type = name; |
| 16 | + } |
| 17 | +} |
| 18 | + |
| 19 | +export function isActionType<T extends Action>(action: Action, actionClass: ActionClass<T>): action is T { |
| 20 | + return action.type == actionClass.prototype.type; |
| 21 | +} |
| 22 | + |
| 23 | +// Middleware for transforming Typed Actions into plain actions |
| 24 | +export const typedToPlain = (store: any) => (next: any) => (action: any) => { |
| 25 | + next((<any>Object).assign({}, action)); |
| 26 | +}; |
| 27 | + |
| 28 | +export abstract class Action { |
| 29 | + type: string; |
| 30 | + constructor() { |
| 31 | + // Make it an own-property (not a prototype property) so that it's included when JSON-serializing |
| 32 | + this.type = this.type; |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +export interface Reducer<TState> extends Function { |
| 37 | + (state: TState, action: Action): TState; |
| 38 | +} |
| 39 | + |
| 40 | +export interface ActionCreatorGeneric<TState> extends Function { |
| 41 | + (dispatch: Dispatch, getState: () => TState): any; |
| 42 | +} |
0 commit comments