Reputation: 463
I'm creating a simple webpage on React + TS with ant design library and I have a problem with types in form component. I created an array to map through them and render form.
https://codesandbox.io/s/relaxed-mountain-vb1b0e?from-embed
That looks an element in array which gives me an error.
const FormItems = [
// {
// name: 'name',
// label: 'Imię/ firma',
// rules: { required: true }, <----- this element is good
// inputType: <Input />,
// },
{
name: 'email',
label: 'Email',
rules: { type: 'email', required: true }, <---- this element giving an error
inputType: <Input />,
},
];
ERROR / / /
Type '{ type: string; required: boolean; }' is not assignable to type 'Rule'.
Type '{ type: string; required: boolean; }' is not assignable to type 'ArrayRule'.
Types of property 'type' are incompatible.
Type 'string' is not assignable to type '"array"'.ts(2322)
And this error occurs in this fragment of code:
{FormItems.map((item) => (
<Form.Item
name={['user', item.name]}
label={item.label}
rules={[item.rules]} <--- item.rules are underlined
>
{item.inputType}
</Form.Item>
))}
Upvotes: 0
Views: 718
Reputation: 1576
Antd provide type definition for rules props. You can import it like this:
import { Rule } from 'antd/es/form';
Now you can define the type of your FormItems List like this:
import { Rule } from 'antd/es/form';
import { ReactNode } from 'react';
type FormItemsListType = {
name: string;
label: string;
rules: Rule[];
inputType: ReactNode;
};
const FormItems: FormItemsListType[] = [
{
name: 'email',
label: 'Email',
rules: [{ type: 'boolean', required: true }],
inputType: <Input />
}
];
Upvotes: 1
Reputation: 11
The prop expects a string
, not a boolean
value, consult the documentation here and here, however, I am unable to reproduce this error, if possible, please try reproducing it on codesandbox.io or a similar service.
{
name: "email",
label: "Email",
rules: {
type: 'boolean',
required: true
},
inputType: <Input />
}
Upvotes: 1