Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: maintain the form types when transforming with useTransform hook #889

Merged
merged 1 commit into from
Aug 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions packages/react-form/src/useTransform.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import type { FormApi, Validator } from '@tanstack/form-core'
import type { FormApi, FormTransform, Validator } from '@tanstack/form-core'

export function useTransform<
TFormData,
TFormValidator extends Validator<TFormData, unknown> | undefined = undefined,
>(
fn: (formBase: FormApi<any, any>) => FormApi<TFormData, TFormValidator>,
deps: unknown[],
) {
): FormTransform<TFormData, TFormValidator> {

Check warning on line 9 in packages/react-form/src/useTransform.ts

View check run for this annotation

Codecov / codecov/patch

packages/react-form/src/useTransform.ts#L9

Added line #L9 was not covered by tests
return {
fn,
deps,
Expand Down
30 changes: 30 additions & 0 deletions packages/react-form/tests/useTransform.test-d.tsx
Original file line number Diff line number Diff line change
@@ -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<any>

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<string>(form.state.values.firstName)

// @ts-expect-error this should be a number
form.state.values.age = 'age'
}
})