Skip to content

Commit

Permalink
add DeclaredMiddlewareType helper type to specify middleware signatur…
Browse files Browse the repository at this point in the history
…e on extended function objects
  • Loading branch information
phryneas committed May 10, 2020
1 parent 0d58077 commit b9a21f1
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 3 deletions.
1 change: 0 additions & 1 deletion src/createActionListenerMiddleware.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,6 @@ describe('createActionListenerMiddleware', () => {
const unsubscribe = store.dispatch(addListenerAction(testAction1, listener))

store.dispatch(testAction1('a'))
// @ts-ignore TODO types
unsubscribe()
store.dispatch(testAction2('b'))
store.dispatch(testAction1('c'))
Expand Down
7 changes: 6 additions & 1 deletion src/createActionListenerMiddleware.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Middleware, Dispatch, AnyAction, MiddlewareAPI, Action } from 'redux'
import { TypedActionCreator } from './mapBuilders'
import { createAction, BaseActionCreator } from './createAction'
import { WithMiddlewareType } from './tsHelpers'

export type When = 'before' | 'after' | undefined
type WhenFromOptions<
Expand Down Expand Up @@ -349,5 +350,9 @@ export function createActionListenerMiddleware<
}
}

return Object.assign(middleware, { addListener, removeListener })
return Object.assign(
middleware,
{ addListener, removeListener },
{} as WithMiddlewareType<typeof middleware>
)
}
19 changes: 18 additions & 1 deletion src/tsHelpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,14 +65,31 @@ export type IsUnknownOrNonInferrable<T, True, False> = AtLeastTS35<
IsEmptyObj<T, True, IsUnknown<T, True, False>>
>

const declaredMiddlewareType: unique symbol = undefined as any
export type WithMiddlewareType<T extends Middleware<any, any, any>> = {
[declaredMiddlewareType]: T
}

/**
* Combines all dispatch signatures of all middlewares in the array `M` into
* one intersected dispatch signature.
*/
export type DispatchForMiddlewares<M> = M extends ReadonlyArray<any>
? UnionToIntersection<
M[number] extends infer MiddlewareValues
? MiddlewareValues extends Middleware<infer DispatchExt, any, any>
? MiddlewareValues extends WithMiddlewareType<
infer DeclaredMiddlewareType
>
? DeclaredMiddlewareType extends Middleware<
infer DispatchExt,
any,
any
>
? DispatchExt extends Function
? DispatchExt
: never
: never
: MiddlewareValues extends Middleware<infer DispatchExt, any, any>
? DispatchExt extends Function
? DispatchExt
: never
Expand Down

0 comments on commit b9a21f1

Please sign in to comment.