chore: improve DispatchingStore typings for dispatch streams

This commit is contained in:
Andrew Bastin
2023-02-17 16:04:29 +05:30
parent b27fe871c4
commit 2545262fc2

View File

@@ -23,12 +23,13 @@ export const defineDispatchers = <
type Dispatch< type Dispatch<
StoreType, StoreType,
DispatchersType extends { [x: string]: DispatcherFunc<StoreType, any> }, DispatchersType extends { [x: string]: DispatcherFunc<StoreType, any> }
Dispatcher extends keyof DispatchersType
> = { > = {
[Dispatcher in keyof DispatchersType]: {
dispatcher: Dispatcher dispatcher: Dispatcher
payload: Parameters<DispatchersType[Dispatcher]>[1] payload: Parameters<DispatchersType[Dispatcher]>[1]
} }
}[keyof DispatchersType]
export default class DispatchingStore< export default class DispatchingStore<
StoreType, StoreType,
@@ -36,9 +37,7 @@ export default class DispatchingStore<
> { > {
#state$: BehaviorSubject<StoreType> #state$: BehaviorSubject<StoreType>
#dispatchers: DispatchersType #dispatchers: DispatchersType
#dispatches$: Subject< #dispatches$: Subject<Dispatch<StoreType, DispatchersType>> = new Subject()
Dispatch<StoreType, DispatchersType, keyof DispatchersType>
> = new Subject()
constructor(initialValue: StoreType, dispatchers: DispatchersType) { constructor(initialValue: StoreType, dispatchers: DispatchersType) {
this.#state$ = new BehaviorSubject(initialValue) this.#state$ = new BehaviorSubject(initialValue)
@@ -70,10 +69,7 @@ export default class DispatchingStore<
return this.#dispatches$ return this.#dispatches$
} }
dispatch<Dispatcher extends keyof DispatchersType>({ dispatch({ dispatcher, payload }: Dispatch<StoreType, DispatchersType>) {
dispatcher,
payload,
}: Dispatch<StoreType, DispatchersType, Dispatcher>) {
if (!this.#dispatchers[dispatcher]) if (!this.#dispatchers[dispatcher])
throw new Error(`Undefined dispatch type '${String(dispatcher)}'`) throw new Error(`Undefined dispatch type '${String(dispatcher)}'`)