简体   繁体   中英

How can you define a type for onSubmit in a Typescript interface?

Within my React app I have an interface in which I also specify the onSubmit method optionally and with the any type (which I want to avoid). So I'm looking for a way to define a type for the onSubmit method.

This is my interface:

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

How can I optimize this interface?

Try this:

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
}

I would suggest to do something like this:

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

Or lets say onSubmit function needs an string param:

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

This you declare onSubmit has type function.

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