add generic initial

This commit is contained in:
Yanick Champoux 2021-10-18 08:46:00 -04:00
parent 85e478c02f
commit 27958a6d14
5 changed files with 42 additions and 7 deletions

View File

@ -6,6 +6,13 @@ vars:
GREETING: Hello, World!
tasks:
tsc: tsc
test: jest
check:
deps: [tsc, test]
'test:types': tsd
docs:
cmds:

View File

@ -14,12 +14,17 @@ import {
augmentMiddlewareApi,
} from './buildMiddleware';
import { Dict } from './types';
import { AggregateDuxState, Dict } from './types';
/**
* Configuration object typically passed to the constructor of the class Updux.
*/
export interface UpduxConfig<TState = unknown> {
export interface UpduxConfig<
TState = any,
TActions = {},
TSelectors = {},
TSubduxes = {},
> {
/**
* Local initial state.
* @default {}
@ -29,7 +34,7 @@ export interface UpduxConfig<TState = unknown> {
/**
* Subduxes to be merged to this dux.
*/
subduxes?: Dict<Updux | UpduxConfig>;
subduxes?: TSubduxes;
/**
* Local actions.
@ -70,7 +75,12 @@ export interface UpduxConfig<TState = unknown> {
mappedReaction?: Function | boolean;
}
export class Updux {
export class Updux<
TState extends any = {},
TActions = {},
TSelectors = {},
TSubduxes extends object = {},
> {
/** @type { unknown } */
#initial = {};
#subduxes = {};
@ -84,7 +94,7 @@ export class Updux {
#mappedSelectors = undefined;
#mappedReaction = undefined;
constructor(config: UpduxConfig) {
constructor(config: UpduxConfig<TState,TActions,TSelectors,TSubduxes>) {
this.#initial = config.initial ?? {};
this.#subduxes = config.subduxes ?? {};
@ -148,7 +158,7 @@ export class Updux {
}
/** @member { unknown } */
get initial() {
get initial() : AggregateDuxState<TState,TSubduxes> {
return this.#memoInitial(this.#initial, this.#subduxes);
}

View File

@ -1,4 +1,4 @@
import { action } from './actions.js';
import { action } from './actions';
test('action generators', () => {
const foo = action('foo');

View File

@ -1,2 +1,20 @@
export type Dict<T> = Record<string, T>;
type Subdux<TState = any> = {
initial: TState
};
type StateOf<D> = D extends { initial: infer I } ? I : unknown;
type Subduxes = Record<string,Subdux>;
export type DuxStateSubduxes<C> = C extends { '*': infer I }
? {
[key: string]: StateOf<I>;
[index: number]: StateOf<I>;
}
: { [K in keyof C]: StateOf<C[K]> };
export type AggregateDuxState<TState, TSubduxes> = TState & DuxStateSubduxes<TSubduxes>;