From de98e30c0b42efd4a172ddc459b97e4b17a50a99 Mon Sep 17 00:00:00 2001 From: Mohammad Hasani Date: Fri, 25 Jan 2019 03:35:53 +0330 Subject: [PATCH] feat: deep immutable reducer type state closes #3 --- src/create-reducer.ts | 3 ++- src/types.ts | 27 +++++++++++++++++++++++++-- 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/src/create-reducer.ts b/src/create-reducer.ts index ffb82c0..e38be0b 100644 --- a/src/create-reducer.ts +++ b/src/create-reducer.ts @@ -4,6 +4,7 @@ import { HandlerMap, } from './create-handler-map' import { merge } from './utils' +import { DeepImmutable } from './types' /** * Reducer factory @@ -21,7 +22,7 @@ export function createReducer>( const handlerMap = merge(...handlerMapsCreator(createHandlerMap)) return ( - state = defaultState, + state = >defaultState, action: HM extends HandlerMap ? T : never ) => { const handler = handlerMap[action.type] diff --git a/src/types.ts b/src/types.ts index 52e8440..c2ae579 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,4 +1,27 @@ +type Primitive = undefined | null | boolean | string | number | Function + +interface DeepImmutableArray extends ReadonlyArray> {} +interface DeepImmutableMap + extends ReadonlyMap, DeepImmutable> {} +type DeepImmutableObject = { readonly [K in keyof T]: DeepImmutable } + +export type Immutable = T extends Primitive + ? T + : T extends Array + ? ReadonlyArray + : T extends Map + ? ReadonlyMap + : Readonly + +export type DeepImmutable = T extends Primitive + ? T + : T extends Array + ? DeepImmutableArray + : T extends Map + ? DeepImmutableMap + : DeepImmutableObject + export type Reducer = ( - prevState: State, + prevState: DeepImmutable, action: Actions -) => State +) => DeepImmutable | State