From b998045e154411d3d570e76edb6319f2befced81 Mon Sep 17 00:00:00 2001 From: Leonardo Montini Date: Fri, 9 Aug 2024 08:51:13 +0200 Subject: [PATCH] fix: maintain the form types when transforming with useTransform hook (#889) --- packages/react-form/src/useTransform.ts | 4 +-- .../react-form/tests/useTransform.test-d.tsx | 30 +++++++++++++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) create mode 100644 packages/react-form/tests/useTransform.test-d.tsx diff --git a/packages/react-form/src/useTransform.ts b/packages/react-form/src/useTransform.ts index d771d9e7c..35905370a 100644 --- a/packages/react-form/src/useTransform.ts +++ b/packages/react-form/src/useTransform.ts @@ -1,4 +1,4 @@ -import type { FormApi, Validator } from '@tanstack/form-core' +import type { FormApi, FormTransform, Validator } from '@tanstack/form-core' export function useTransform< TFormData, @@ -6,7 +6,7 @@ export function useTransform< >( fn: (formBase: FormApi) => FormApi, deps: unknown[], -) { +): FormTransform { return { fn, deps, diff --git a/packages/react-form/tests/useTransform.test-d.tsx b/packages/react-form/tests/useTransform.test-d.tsx new file mode 100644 index 000000000..0fe1f0da3 --- /dev/null +++ b/packages/react-form/tests/useTransform.test-d.tsx @@ -0,0 +1,30 @@ +import { assertType, it } from 'vitest' +import { formOptions, mergeForm, useForm, useTransform } from '../src' +import { type ServerFormState } from '../src/nextjs/types' + +it('should maintain the type of the form', () => { + const state = {} as ServerFormState + + const formOpts = formOptions({ + defaultValues: { + firstName: '', + age: 123, + } as const, + }) + + function Comp() { + const form = useForm({ + ...formOpts, + transform: useTransform( + (baseForm) => mergeForm(baseForm, state), + [state], + ), + }) + + assertType<123>(form.state.values.age) + assertType(form.state.values.firstName) + + // @ts-expect-error this should be a number + form.state.values.age = 'age' + } +})