简体   繁体   中英

ReactJS | Typescript type for onClick. `onclick does not exist on type`x`

I have the below method, that renders a delete Icon, and I use it in my main Container. Everything works fine. The only problem, I have, and it is a small cosmetic one, is an any type that I cannot figure out, what that type is.

import React from 'react';
import Icon from './Icon';

const DeleteActionRenderer = (options: any): Function => (cell: string, row: string): JSX.Element => {
  const deleteActionClick = options.onClick({ cell, row }); // The error is here. On options.onClick.
  return (
    <div>
      <a href="#" className="text-danger p-1 text-lg" onClick={deleteActionClick}>
        <Icon icon="trash" />
      </a>
    </div>
  );
};

export default DeleteActionRenderer;

As you can see, options have any as a type. I cannot figure out, what options is. Nothing except any works. object, string, number, Function, MouseEvents, SyntheticEvent . Not even unknown .

The only type that works is any .

I console.log(options, typeOf options), and it prints out an object. See below:

{onClick: ƒ}
onClick: ƒ (_ref2)
arguments: (...)
caller: (...)
length: 1
name: ""
prototype: {constructor: ƒ}
__proto__: ƒ ()
[[FunctionLocation]]: index.tsx:146
[[Scopes]]: Scopes[5]
__proto__: Object

Any ideas? This any is like a sore thumb, for a little while now. I cannot figure it out at all. Thank you for your time.

The code above looks to me like a HOC (High Order Component) https://reactjs.org/docs/higher-order-components.html

I can see in your code that the way you are using DeleteActionRenderer is not correct as the options object in this case is part of props so it will be coming in the function that you return from DeleteActionRenderer and not in DeleteActionRenderer itself.

In your case, for options type will be:

type Options = {
   onClick: Function
}

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM