Skip to main content

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.

Edit RCF - TypeScript

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 Hooks#

We 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>();
๏ผฆ;
// Working without "validate" option
const props = useFieldArray<FieldValue>();
// Working with "validate" option
const props = useFieldArray<FieldValue, FormValues>({
validate: (value) => {
/* ... */
},
});

Making Field's Name Type-safe#

Some 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.