Can't assign specific type as an argument to a generic

I am trying to set an interface where I can pass arguments without specifying its type.

// Wrapper.tsx
interface Props extends MenuProps, ChakraProps {
  handleTagClick: <T>(args?: T) => void
}

export const Wrapper: FC<Props> = ({ handleTagClick }): JSX.Element => {
  return(
    <Button 
       {...(
          handleTagClick && { 
            onClick: () => handleTagClick({ ...dummyQuestion, type }) })
       }
    />
  )
}

Then I call that component where the error comes:

export const Container = () => {

  const { addNewThing } = useMyHook()

  // The error comes from this line
  return <Wrapper handleTagClick={addNewThing} />
}

The error:

Type '(question: VariableConfig) => void' is not assignable to type '<T>(args?: T | undefined) => void'.
  Types of parameters 'question' and 'args' are incompatible.
    Type 'T | undefined' is not assignable to type 'VariableConfig'.
      Type 'undefined' is not assignable to type 'VariableConfig'.
Wrapper.tsx(10, 3): The expected type comes from property 'handleTagClick' which is declared here on type 'IntrinsicAttributes & Partial<Props> & { children?: ReactNode; }'

What am I doing wrong?

38 thoughts on “Can't assign specific type as an argument to a generic”

  1. You designed the component so that it is accepting the function with the argument of type unknown among the props. That means, inside the component, it supposed that this function could be provided with such an argument. When you pass the function accepting an argument of only VariableConfig type it might result in an error if it would have an argument of another type (unknown). It is not expected. To fix that:

    interface Props extends MenuProps, ChakraProps {
      handleTagClick: (args: VariableConfig) => void
    }
    
    Reply

Leave a Comment