Skip to content

Commit

Permalink
feat: deep immutable reducer type state
Browse files Browse the repository at this point in the history
closes #3
  • Loading branch information
Mohammad Hasani committed Feb 14, 2019
1 parent 35372da commit de98e30
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
3 changes: 2 additions & 1 deletion src/create-reducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
HandlerMap,
} from './create-handler-map'
import { merge } from './utils'
import { DeepImmutable } from './types'

/**
* Reducer factory
Expand All @@ -21,7 +22,7 @@ export function createReducer<State, HM extends HandlerMap<State, any>>(
const handlerMap = merge(...handlerMapsCreator(createHandlerMap))

return (
state = defaultState,
state = <DeepImmutable<State>>defaultState,
action: HM extends HandlerMap<State, infer T> ? T : never
) => {
const handler = handlerMap[action.type]
Expand Down
27 changes: 25 additions & 2 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,27 @@
type Primitive = undefined | null | boolean | string | number | Function

interface DeepImmutableArray<T> extends ReadonlyArray<DeepImmutable<T>> {}
interface DeepImmutableMap<K, V>
extends ReadonlyMap<DeepImmutable<K>, DeepImmutable<V>> {}
type DeepImmutableObject<T> = { readonly [K in keyof T]: DeepImmutable<T[K]> }

export type Immutable<T> = T extends Primitive
? T
: T extends Array<infer U>
? ReadonlyArray<U>
: T extends Map<infer K, infer V>
? ReadonlyMap<K, V>
: Readonly<T>

export type DeepImmutable<T> = T extends Primitive
? T
: T extends Array<infer U>
? DeepImmutableArray<U>
: T extends Map<infer K, infer V>
? DeepImmutableMap<K, V>
: DeepImmutableObject<T>

export type Reducer<State, Actions> = (
prevState: State,
prevState: DeepImmutable<State>,
action: Actions
) => State
) => DeepImmutable<State> | State

0 comments on commit de98e30

Please sign in to comment.