Search code examples
javascriptreactjstypescripttypesantd

Typescript issue while mapping through array from antd form


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>
        ))}

Solution

  • 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 />
        }
    ];