TypeScript Support
React Cool Form is written in TypeScript, so the library's types will always be up-to-date. When working with TypeScript, we can define a FormValues
type to support the form's values.
import { useForm } from "react-cool-form";
interface FormValues { firstName: string; lastName: string;}
const App = () => { const { form } = useForm<FormValues>({ defaultValues: { firstName: "Welly", lastName: true, // ❌ Type "boolean" is not assignable to type "string" }, onSubmit: (values) => { console.log("First Name: ", values.firstName); console.log("Middle Name: ", values.middleName); // ❌ Property "middleName" does not exist on type "FormValues" }, });
return ( <form ref={form}> <input name="firstName" /> <input name="lastName" /> <input type="submit" /> </form> );};
#
TypeScript and HooksWe can provide the FormValues
type to the following hooks:
interface FormValues { firstName: string; lastName: string;}
const methods = useForm<FormValues>();
const methods = useFormMethods<FormValues>();
const props = useFormState<FormValues>();
const props = useControlled<FormValues>();F;// Working without "validate" optionconst props = useFieldArray<FieldValue>();// Working with "validate" optionconst props = useFieldArray<FieldValue, FormValues>({ validate: (value) => { /* ... */ },});
#
Making Field's Name Type-safeSome folks are asking about the type-safe of a field's name, however we can achieve that via TypeScript's Enums.
enum FieldNames { "name" = "name",}
const App = () => { const { form } = useForm({ defaultValues: { [FieldNames.email]: "Welly", // ❌ Property "email" does not exist on type "typeof FieldNames" }, });
return ( <form ref={form}> <input name={FieldNames.email} // ❌ Property "email" does not exist on type "typeof FieldNames" /> </form> );};
🧐 You can dig more useful types of this library to build a strongly typed form.