skip to Main Content
import React from 'react'

export default function Test() {
  const handleClick = () => (label: string) => {
    console.log('label: ' + label)
  }

  return <button onClick={handleClick('red one')}>click me</button>
}

TypeScript compiler is complaining on my code, what I have done wrong?

Type '(label: string) => void' is not assignable to type 'MouseEventHandler<HTMLButtonElement>'.
  Types of parameters 'label' and 'event' are incompatible.
    Type 'MouseEvent<HTMLButtonElement, MouseEvent>' is not assignable to type 'string'.ts(2322)
index.d.ts(1494, 9): The expected type comes from property 'onClick' which is declared here on type 'DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>'

2

Answers


  1. Chosen as BEST ANSWER

    It's the other way around,

    it should be

    (label: string) => (e: any) => {
    

    instead of

    (e: any) => (label: string) => {
    
    import React from 'react'
    
    export default function Test() {
      const handleClick = (label: string) => (e: any) => {
        console.log('label: ' + label)
      }
    
      return <button onClick={handleClick('red one')}>click me</button>
    }
    

  2. The handleClick function doesn’t expect any type of parameter but you are passing it a string.

    It should be:

    import React from 'react'
    
    export default function Test() {
      const handleClick = (label: string) => () => {
        console.log('label: ' + label)
      }
    
      return <button onClick={handleClick('red one')}>click me</button>
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search