cubefox
cubefox

Reputation: 1301

type onClick function for html components

Every time I try to type something like onClick in my component like this:

export interface IClearButton extends SpaceProps {
  onClick: Function;
}

export const ClearButton: React.FC<IClearButton> = ({onClick}) => {
  return (
    <button onClick={onClick}>
      <SomeComponent />
    </button>
  );
};

I end up with an error like this:

Type '{ onClick: Function; }' is not assignable to type 'IntrinsicAttributes & IClearButton & { children?: ReactNode; }'.
  Property 'onClick' does not exist on type 'IntrinsicAttributes & IClearButton & { children?: ReactNode; }'

Currently, I just end up saying onClick: any which is less than ideal. How can I either extend the intrinsic onClick type or force overwrite it with Function in my type definition?

Upvotes: 0

Views: 52

Answers (1)

nickbullock
nickbullock

Reputation: 6589

You should use interfaces DetailedHTMLProps and InputHTMLAttributes with generics.

import React, { DetailedHTMLProps, InputHTMLAttributes } from 'react';

interface MyProps extends DetailedHTMLProps<
    InputHTMLAttributes<HTMLButtonElement>,
    HTMLButtonElement
  > {
    name: string;
}

In this case type of onClick will be var onClick: (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void.
Created stackblitz for you.

Upvotes: 1

Related Questions