How can I properly document this generic function?

Viewed 1091
/**
 * Wraps a styled component to supply default props
 * @template {T} - Component type
 * @template {TDefaults} - Default props
 * @param {T} component  - Our styled component object
 * @param {TDefaults} defaultProps - The object's default props
 * @returns the styled component with default props applied
 */
export function withDefault<T extends { defaultProps?: Partial<TDefaults> }, TDefaults>(component: T, defaultProps: TDefaults): T & { defaultProps: TDefaults } {
  // eslint-disable-next-line no-param-reassign
  component.defaultProps = defaultProps;
  // Cast to any necessary as we can't infer styled component type
  return component as any;
}

This returns these errors:

  5:0    warning  The type 'T' is undefined          jsdoc/no-undefined-types
  6:0    warning  The type 'TDefaults' is undefined  jsdoc/no-undefined-types
  9:41   warning  Missing JSDoc comment              jsdoc/require-jsdoc
  9:135  warning  Missing JSDoc comment              jsdoc/require-jsdoc
1 Answers

For JSDoc @template, the thing inside the braces {...} is the constraint, and the template variable name should be placed after the braces. So the correct syntax should be:

/**
 * Wraps a styled component to supply default props
 * @template {{ defaultProps?: Partial<TDefaults> }} T - Component type
 * @template {any} TDefaults - Default props
 * @param {T} component  - Our styled component object
 * @param {TDefaults} defaultProps - The object's default props
 * @returns the styled component with default props applied
 */
export function withDefault<T extends { defaultProps?: Partial<TDefaults> }, TDefaults>(component: T, defaultProps: TDefaults): T & { defaultProps: TDefaults } {
  // eslint-disable-next-line no-param-reassign
  component.defaultProps = defaultProps;
  // Cast to any necessary as we can't infer styled component type
  return component as any;
}

You also need to set the eslint option settings.jsdoc.mode to typescript according to this doc to suppress the error.

Related