UNPKG

fielder

Version:

A field-first form library for React and React Native

55 lines (36 loc) 1.25 kB
# Type safety _Typing fields and forms with `Fielder`._ ## Why use types By using types with Fielder, you can: - Enforce field value types (setters and return values) - Enforce field names (prevent typos) ## Basic typing A _form definition_ type declares all the possible field names and their values. ```ts type MyFormState = { username: string; password: string; saveCredentials: boolean; }; ``` Passing the _form defintion_ to `useField`, `useForm`, `useFormContext`, or `useSubmit` will ensure the correct types. ```tsx const [fieldProps] = useField<MyFormState>({ name: 'password' }); ``` ## Advanced typing If you prefer not to manually type every hook call, you can re-export them. > You'll want to follow this process for each form you create. Create a `fielder.ts` file alongside your form's root component and copy the example below. ```ts import { typedHooks } from 'fielder'; import { FormType } from './types'; export const { useField, useForm, useFormContext } = typedHooks<FormType>(); ``` Now when using any of the _Fielder_ hooks, import them from the file you just created. ```tsx import { useField } from '../fielder'; // ... const [fieldProps] = useField({ name: 'invalidName', // Type error! }); ```