【问题标题】:How can you define a type for onSubmit in a Typescript interface?如何在 Typescript 接口中为 onSubmit 定义类型?
【发布时间】:2021-01-07 08:31:59
【问题描述】:

在我的 React 应用程序中,我有一个界面,在该界面中我还可以选择指定 onSubmit 方法并使用 any 类型(我想避免)。所以我正在寻找一种方法来定义 onSubmit 方法的类型。

这是我的界面:

export interface CustomInterface {
  product?: ProductClass;
  loggedInUser: UserClass;
  headerTitle?: (s: string) => any;
  onSubmit?: any; // Here I need a better type
}

如何优化这个界面?

【问题讨论】:

  • 我假设 onSubmit 是一个回调,给定命名约定。你已经为 headerTitle 使用了一个函数类型,你有什么理由不能再这样做吗?
  • @jonrsharpe 是的,但是 headerTitle 返回了一个简单的字符串。 OnSubmit 的作用远不止这些,不是吗?
  • 我们不知道,我们看不到它是如何使用的。它大概会是一个 void 函数,它需要一些数据,但我们无法告诉你这些数据将具有什么形状。
  • 在我的例子中,onSubmit 方法被传递给另外两个父组件,并调用父组件中的处理程序,在其中调度操作。
  • 我们需要知道它的签名和返回类型。

标签: javascript reactjs typescript react-typescript


【解决方案1】:

我建议这样做:

export interface CustomInterface {
  product?: ProductClass;
  loggedInUser: UserClass;
  headerTitle?: (s: string) => any;
  onSubmit?(): void;
}

或者说 onSubmit 函数需要一个字符串参数:

export interface CustomInterface {
  product?: ProductClass;
  loggedInUser: UserClass;
  headerTitle?: (s: string) => any;
  onSubmit?(s: string): void;
}

你声明的这个 onSubmit 有类型函数。

【讨论】:

    【解决方案2】:

    试试这个:

    export interface CustomInterface {
      product?: ProductClass;
      loggedInUser: UserClass;
      headerTitle?: (s: string) => any;
      onSubmit?: (data:Define your type here like string,boolean and so on)=>void // Here I need a better type
    }
    

    【讨论】:

      猜你喜欢
      • 2021-07-06
      • 2020-04-26
      • 1970-01-01
      • 2021-12-08
      • 2022-08-07
      • 2015-07-27
      • 1970-01-01
      • 2021-06-19
      相关资源
      最近更新 更多