Home > Net >  Use of typescript generics for extended parametres
Use of typescript generics for extended parametres

Time:05-05

My purpose is simple: I want to find a way of using generics for extended parametres, in this example, throwData is the thing I am interested in. Instead of any, I want to use something more informative such as generic. Is there any way I can stuff like that?

 titleStylesCondition<
    IP extends {
      hasOwnProperty: (a: string) => boolean;
      throwData?: any;
      title?: string;
    }
  >(itemProps: IP) {
    const { palette, isDark } = this.context;
    const styles = getStyles(palette, isDark);
    const titleStyles = this.get("props.titleStyles", {});
    if (
      itemProps.hasOwnProperty("Industry") ||
      itemProps.throwData.hasOwnProperty("Auto") ||
      itemProps.title === "BMW"
    ) {
      return styles.autoStyling;
  }

CodePudding user response:

Sure, just add another generic to hold its type:

 titleStylesCondition<
    IP extends {
      hasOwnProperty: (a: string) => boolean;
      throwData?: ThrowData;
      title?: string;
    },
    ThrowData,
  >(itemProps: IP) {

Most of the time, TypeScript can infer this ThrowData generic properly.

  • Related