如何在TypeScript中用JSDoc记录provider-pattern函数?
记录Provider模式返回函数的方案
一、JSDoc正确写法
要让IDE识别返回的函数,你需要在提供者函数的JSDoc里明确标注返回值是一个函数类型,并说明该函数的参数和返回值。
写法1:直接在@returns中定义函数类型
/** * 创建一个绑定指定接口地址的调用函数 * @param {string} endpointToCall - 目标接口的地址 * @returns {function(string): Promise<null>} 接收访问令牌的异步函数,调用后返回null */ export const callEndpointProvider = (endpointToCall: string) => async (accessToken: string): Promise<null> => { return null }
写法2:用@typedef复用函数类型
如果多个Provider都返回同类型的函数,先定义类型别名再引用可以提升复用性:
/** * 接口调用函数类型:接收访问令牌,异步返回null * @typedef {function(string): Promise<null>} EndpointCaller */ /** * 创建绑定指定接口的调用函数 * @param {string} endpointToCall - 要调用的接口地址 * @returns {EndpointCaller} 配置完成的接口调用函数 */ export const callEndpointProvider = (endpointToCall: string) => async (accessToken: string): Promise<null> => { return null }
二、TypeScript原生替代方案
既然你使用的是TypeScript,直接用类型别名定义返回函数的类型,配合极简JSDoc就能让IDE给出清晰提示,无需复杂的JSDoc语法:
// 定义返回函数的类型 type EndpointCaller = (accessToken: string) => Promise<null>; /** * 创建绑定指定接口的调用函数 * @param endpointToCall - 目标接口地址 */ export const callEndpointProvider = (endpointToCall: string): EndpointCaller => async (accessToken) => { return null }
这样,当你调用callEndpointProvider('/api/user')得到的函数,IDE会自动提示它需要接收一个string类型的accessToken,并返回Promise<null>。
内容的提问来源于stack exchange,提问作者Joe Howard
相关产品推荐
相关产品推荐

