我如何正确记录此通用功能?

问题描述 投票:1回答:1
/**
 * 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;
}

这将返回这些错误:

  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
typescript jsdoc
1个回答
0
投票

对于JSDoc @template,花括号{...}内的内容是constraint,并且模板变量名称应放在花括号后。因此,correct syntax应为:

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

您还需要根据settings.jsdoc.mode将eslint选项typescript设置为this doc以抑制该错误。

© www.soinside.com 2019 - 2024. All rights reserved.