Skip to content

Commit

Permalink
types(vest): Automatically infer state type from state key
Browse files Browse the repository at this point in the history
  • Loading branch information
ealush committed Apr 26, 2022
1 parent 4d15f14 commit ab4a29e
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 16 deletions.
6 changes: 6 additions & 0 deletions packages/vest/src/core/state/createStateRef.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,9 @@ export default function createStateRef(
}

export type StateRef = ReturnType<typeof createStateRef>;

type StateKeys = keyof StateRef;

export type StateKey<T extends StateKeys> = ReturnType<StateRef[T]>;
export type StateValue<T extends StateKeys> = StateKey<T>[0];
export type StateSetter<T extends StateKeys> = StateKey<T>[1];
22 changes: 6 additions & 16 deletions packages/vest/src/core/state/stateHooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,10 @@ import asArray from 'asArray';
import createCache from 'cache';
import type { NestedArray } from 'nestedArray';
import * as nestedArray from 'nestedArray';
import type { StateHandlerReturn } from 'vast';

import VestTest from 'VestTest';
import type { StateRef } from 'createStateRef';
import type { StateKey, StateRef, StateValue } from 'createStateRef';
import ctx from 'ctx';
import type { SuiteResult } from 'produceSuiteResult';

// STATE REF
export function useStateRef(): Exclude<StateRef, void> {
Expand All @@ -16,28 +14,20 @@ export function useStateRef(): Exclude<StateRef, void> {
}

// STATE KEYS
export function useSuiteId(): string {
export function useSuiteId(): StateValue<'suiteId'> {
return useStateRef().suiteId()[0];
}
export function useSuiteName(): string | void {
export function useSuiteName(): StateValue<'suiteName'> {
return useStateRef().suiteName()[0];
}
export function useTestCallbacks(): StateHandlerReturn<{
fieldCallbacks: Record<string, ((res: SuiteResult) => void)[]>;
doneCallbacks: ((res: SuiteResult) => void)[];
}> {
export function useTestCallbacks(): StateKey<'testCallbacks'> {
return useStateRef().testCallbacks();
}
export function useOptionalFields(): StateHandlerReturn<
Record<string, (() => boolean) | boolean>
> {
export function useOptionalFields(): StateKey<'optionalFields'> {
return useStateRef().optionalFields();
}

export function useTestObjects(): StateHandlerReturn<{
prev: NestedArray<VestTest>;
current: NestedArray<VestTest>;
}> {
export function useTestObjects(): StateKey<'testObjects'> {
return useStateRef().testObjects();
}

Expand Down

0 comments on commit ab4a29e

Please sign in to comment.