Typescript
When working with react-flexyform
there are many ways in which we can guarantee type safety both in the form configuration or when interracting with the form store.
Form component mapping keys and params
A useful prerequisite is to declare global mappings between the formComponentMappingKeys
and the componentParams
they accept.
We do this by defining the FormFieldComponentMappings
, FormUiComponentMappings
and FormWrapperComponentMappings
in the global
scope. We can define the ComponentWrapperParams
interface to add common componentParams
properties to all 'field' and 'ui' components.
For example:
In this way, using the typeSafeFieldComponent
, typeSafeUiComponent
and typeSafeWrapperComponent
will ensure type safety when configuring our forms.
Form configuration
It is recommended to to declare the context type in the global
scope.
When creating the formStore
, it's recommended to use the generic slot and provide a type with the form fields and the value types, this way it will also ensure the correct field names in the components
.
If the types are not provided the useCreateFormStore hook will infer the possible field names from the initialData (if provided).
Form store
When using the form store instance via the useFormStore
hook it is recommended to provide the type of the form fields in the generic slot.
We usually do not want to explicitly define the form fields type when using useParentFormStore, as in generic components we should not rely on specific fields to exist in every form.
But we will still get the type safety for the context properties defined in the global scope.