如何编写带类型参数的@typedef?(类似CustomEvent的detail类型)
问题描述
我定义了一个描述API响应的JSDoc类型:
/** * @typedef {{ * status: string, * code: number, * type: string, * data: T[], * }} ApiResponse */
其中T可以是API返回的任意DTO类型。
在处理特定API请求时,我希望像指定CustomEvent的detail属性类型那样,给T指定具体类型,示例代码如下:
/** * @param {CustomEvent<DialogAction>} event */ function ClickHandler(event) { api.query(event.detail.action, { id: event.detail.id, }).then( /** @param {ApiResponse<DataType>} response */ (response) => do.smth(response.data[0].???); ); }
目前编辑器能正确提示event.detail.id和event.detail.action,但无法识别response.data[0]的字段。
请问该如何编写类型定义,让语法分析器能识别这些字段?是需要修改现有的@typedef,还是采用其他方式(比如编写*.d.ts声明)?
解决方案
方法一:修改现有JSDoc定义,显式声明泛型参数
当前的ApiResponse定义未正确声明泛型参数,导致编辑器无法推断T的具体类型。只需添加@template标签明确泛型:
/** * @template T * @typedef {{ * status: string, * code: number, * type: string, * data: T[], * }} ApiResponse */
修改后,当你使用ApiResponse<DataType>时,编辑器会自动将data数组的元素类型关联到DataType,response.data[0]就能正常提示对应的字段了。
方法二:使用TypeScript声明文件(*.d.ts)
如果项目支持,可以创建api.d.ts文件,用TS语法定义泛型接口:
export interface ApiResponse<T> { status: string; code: number; type: string; data: T[]; }
之后在JS文件的JSDoc中直接引入使用:
/** * @param {import('./api.d.ts').ApiResponse<DataType>} response */
这种方式对编辑器的类型支持更完善,适合大型项目。
注意事项
无论采用哪种方式,都需要确保DataType本身有明确的JSDoc类型定义,比如:
/** * @typedef {{ * id: number, * name: string, * // 其他字段 * }} DataType */
只有DataType的类型被正确定义,编辑器才能识别并提示它的属性。
内容的提问来源于stack exchange,提问作者AnrDaemon
相关产品推荐
相关产品推荐

