【问题标题】:Define prop's type for any Function React Typescript为任何 Function React Typescript 定义 prop 的类型
【发布时间】:2020-11-03 21:46:20
【问题描述】:

我正在键入组件的道具,其中func 可以是从其父级传递的任何函数

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

组件:

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

但我收到以下错误:

类型参数'Function | undefined' 不能分配给 '((value: void) => void | PromiseLike) | 类型的参数空 |未定义'。

我应该使用什么类型来定义func 等于任何函数?

【问题讨论】:

标签: javascript typescript


【解决方案1】:

通常(不一定是 React),您可以表达任何函数的类型,例如

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

【讨论】:

  • 那是错误的添加类型的方法。你可以添加 onClick: () => void;或 onChange: (id: number) => void 这样。你可以参考这个github.com/typescript-cheatsheets/react-typescript-cheatsheet
  • @VijayPalaskar 是问题的关键,能够描述 any 函数,无论有无参数或返回值。模式的有效性是另一回事.如果是这种情况,对不同的事件使用不同的回调可能是个好主意,但我们这里没有足够的代码来决定
【解决方案2】:

改变你的界面:

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
}

【讨论】:

    【解决方案3】:

    您正在分配不推荐的方式。 更改您的界面以通过以下方式定义

        /** 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;
    

    你可以参考这个

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

    【讨论】:

      猜你喜欢
      • 2018-03-01
      • 2019-10-06
      • 2017-02-17
      • 2020-10-07
      • 1970-01-01
      • 2019-10-23
      • 2020-08-05
      • 2019-08-27
      • 2020-01-12
      相关资源
      最近更新 更多