0
votes

I'm tying to type Component's props, where func could be any function passed down from it's parent

interface TProps {
    func?: Function
    children?: ReactNode
}

Component:

return (
    <button
        onClick={props.func}
    >
        {props.children}
    </button>
)

But I'm getting the following error:

Argument of type 'Function | undefined' is not assignable to parameter of type '((value: void) => void | PromiseLike) | null | undefined'.

What type should I use to define that func equals any function?

3
you can add onClick: () => void; or onChange: (id: number) => void in this way. You can refer this github.com/typescript-cheatsheets/react-typescript-cheatsheetVijay Palaskar

3 Answers

2
votes

Generally (not necessarily React), you could express the type for any function like

fn: (...args: any[]) => any
1
votes

change your Interface:

interface TProps {
    func?: () => void, // now in () you can pass any argument type, also in place of void, you can define any return type
    children?: ReactNode
}
0
votes

You are assigning the way that's not recommended. change your interface to define in the following ways

    /** any function as long as you don't invoke it (not recommended) */
      onSomething: Function;
     /** function that doesn't take or return anything (VERY COMMON) */
      onClick: () => void;
     /** function with named prop (VERY COMMON) */
      onChange: (id: number) => void;
    /** alternative function type syntax that takes an event (VERY COMMON) */
       onClick(event: React.MouseEvent<HTMLButtonElement>): void;

You can refer this

https://github.com/typescript-cheatsheets/react-typescript-cheatsheet