Home > Enterprise >  TS type for Material-UI MenuItem ForwardRef
TS type for Material-UI MenuItem ForwardRef

Time:01-25

I'm trying to wrap a menuItem from material-ui, and wrap it with forwardRef.

Typescript complains that in forwardRef<MenuItem, Props> TS2749: 'MenuItem' refers to a value, but is being used as a type here. Did you mean 'typeof MenuItem'?

But MenuItem is type annotated and should be working fine. Changing the code to typeof MenuItem doesn't help as then TS complains at the place where I am assigning the ref on MenuItem:

TS2769: No overload matches this call

[...] Type 'HTMLLIElement' provides no match for the signature '<C extends ElementType>(props: { component: C; } & { button: false; } & { alignItems?: "center" | "flex-start" | undefined; autoFocus?: boolean | undefined; button?: boolean | undefined; ... 7 more ...; selected?: boolean | undefined; } & CommonProps<...> & Omit<...>): Element'.

So what should be the type in forwardRef then?

import React, { forwardRef } from 'react'
import MenuItem from '@material-ui/core/MenuItem'


type Props = {...}

export const InputSelectOption = forwardRef<MenuItem, Props>(
  function InputSelectOption (props: Props, ref): JSX.Element {
    return (
      <MenuItem {...props} ref={ref}>
        [...]
      </MenuItem>
    )
  })

CodePudding user response:

The correct type to use is HTMLLIElement.

From the source: enter image description here

  •  Tags:  
  • Related