Skip to content

Commit

Permalink
Account for optional on keys. Fixes #9
Browse files Browse the repository at this point in the history
  • Loading branch information
Cassio Zen committed May 14, 2021
1 parent bc5f37d commit e6502fa
Showing 1 changed file with 3 additions and 5 deletions.
8 changes: 3 additions & 5 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ type Transition<C> =
guard?: (context: C) => boolean;
};

type KeysOfTransition<C, Obj> = Obj extends Record<PropertyKey, Transition<C>> ? keyof Obj : never;
type KeysOfTransition<Obj> = Obj extends { on: { [key: string]: Transition<any> } } ? keyof Obj['on'] : never;

interface BaseStateConfig<C> {
on?: {
Expand All @@ -22,8 +22,6 @@ interface BaseConfig {
};
}

type TransitionEvent<C, T extends Record<PropertyKey, BaseStateConfig<C>>> = T[keyof T]['on'];

type ContextUpdater<C> = (updater: (context: C) => C) => void;

interface MachineStateConfig<C> extends BaseStateConfig<C> {
Expand All @@ -46,7 +44,7 @@ const getReducer = <
Context extends Record<PropertyKey, any>,
Config extends BaseConfig,
State extends keyof Config['states'],
Event extends KeysOfTransition<Context, TransitionEvent<Context, Config['states']>>
Event extends KeysOfTransition<Config['states'][keyof Config['states']]>
>(
config: Config
) =>
Expand Down Expand Up @@ -100,7 +98,7 @@ export default function useStateMachine<Context extends Record<PropertyKey, any>
return function useStateMachineWithContext<Config extends MachineConfig<Context>>(config: Config) {
type IndexableState = keyof typeof config.states;
type State = keyof Config['states'];
type Event = KeysOfTransition<Context, TransitionEvent<Context, Config['states']>>;
type Event = KeysOfTransition<Config['states'][keyof Config['states']]>;

const initialState = useConstant(() => ({
value: config.initial as State,
Expand Down

0 comments on commit e6502fa

Please sign in to comment.