reactjstypescriptantd

Ant Design: Correct type of Menu onClick event parameter


I am trying to use a navigation component from Antd (https://ant.design/components/menu), but it's giving me this error: Parameter 'e' implicitly has an 'any' type.

I have tried doing e: React.MouseEvent<HTMLElement> but then the error shifts to e.key: Property 'key' does not exist on type 'MouseEvent<HTMLInputElement, MouseEvent>'.

Following is my App.tsx:

import { AppstoreOutlined, MailOutlined, SettingOutlined } from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { Menu } from 'antd';

const items: MenuProps['items'] = [
  {
    label: 'Navigation One',
    key: 'mail',
    icon: <MailOutlined />,
  },
  {
    label: 'Navigation Two',
    key: 'app',
    icon: <AppstoreOutlined />,
    disabled: true,
  },
  {
    label: 'Navigation Three - Submenu',
    key: 'SubMenu',
    icon: <SettingOutlined />,
    children: [
      {
        type: 'group',
        label: 'Item 1',
        children: [
          {
            label: 'Option 1',
            key: 'setting:1',
          },
          {
            label: 'Option 2',
            key: 'setting:2',
          },
        ],
      },
      {
        type: 'group',
        label: 'Item 2',
        children: [
          {
            label: 'Option 3',
            key: 'setting:3',
          },
          {
            label: 'Option 4',
            key: 'setting:4',
          },
        ],
      },
    ],
  },
  {
    label: (
      <a href="https://ant.design" target="_blank" rel="noopener noreferrer">
        Navigation Four - Link
      </a>
    ),
    key: 'alipay',
  },
];

const App: React.FC = () => {
  const [current, setCurrent] = useState('mail');

  const onClick: MenuProps['onClick'] = (e) => {
    console.log('click ', e);
    setCurrent(e.key);
  };

  return <Menu onClick={(onClick)} selectedKeys={[current]} mode="horizontal" items={items} />;
};

export default App;

I am new to this and have already spent many hours trying to fix this, any help is highly appreciated! Thank you!


Solution

  • The correct type of e is the MenuInfo interface defined in the react-component library (rc-menu). Unfortunately, this type isn't exported. As a workaround, you can use the following code to indirectly reference the MenuInfo interface:

    const onClick: MenuProps['onClick'] = (e: Parameters<MenuProps['onClick']>[0]) => {
    

    The Parameters utility type returns an array type containing the parameter types of the specified function, and the [0] indexer returns the type of the first (and only) parameter.