From ab4a29e780517433bf3753a37683484d9f5407b8 Mon Sep 17 00:00:00 2001 From: ealush Date: Thu, 14 Apr 2022 22:36:20 +0300 Subject: [PATCH] types(vest): Automatically infer state type from state key --- .../vest/src/core/state/createStateRef.ts | 6 +++++ packages/vest/src/core/state/stateHooks.ts | 22 +++++-------------- 2 files changed, 12 insertions(+), 16 deletions(-) diff --git a/packages/vest/src/core/state/createStateRef.ts b/packages/vest/src/core/state/createStateRef.ts index 90783c76f..4e1e5dd03 100644 --- a/packages/vest/src/core/state/createStateRef.ts +++ b/packages/vest/src/core/state/createStateRef.ts @@ -34,3 +34,9 @@ export default function createStateRef( } export type StateRef = ReturnType; + +type StateKeys = keyof StateRef; + +export type StateKey = ReturnType; +export type StateValue = StateKey[0]; +export type StateSetter = StateKey[1]; diff --git a/packages/vest/src/core/state/stateHooks.ts b/packages/vest/src/core/state/stateHooks.ts index a55b62fd2..fd802ed8a 100644 --- a/packages/vest/src/core/state/stateHooks.ts +++ b/packages/vest/src/core/state/stateHooks.ts @@ -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 { @@ -16,28 +14,20 @@ export function useStateRef(): Exclude { } // 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 void)[]>; - doneCallbacks: ((res: SuiteResult) => void)[]; -}> { +export function useTestCallbacks(): StateKey<'testCallbacks'> { return useStateRef().testCallbacks(); } -export function useOptionalFields(): StateHandlerReturn< - Record boolean) | boolean> -> { +export function useOptionalFields(): StateKey<'optionalFields'> { return useStateRef().optionalFields(); } -export function useTestObjects(): StateHandlerReturn<{ - prev: NestedArray; - current: NestedArray; -}> { +export function useTestObjects(): StateKey<'testObjects'> { return useStateRef().testObjects(); }