gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 20:56:17 25 4
gpt4 key购买 nike

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

最佳答案

对于 JSDoc @template ,大括号里面的东西{...}是约束,模板变量名应该放在大括号之后。所以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;
}

您还需要设置 eslint 选项 settings.jsdoc.modetypescript根据 this doc来抑制错误。

关于typescript - 如何正确记录此通用功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60888458/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com