JSDoc:如何在 NodeJS 中记录快速请求和响应对象中的自定义属性和方法?

问题描述 投票:0回答:1

我正在使用 JavaScript 开发 Express.js 项目,并希望使用 JSDoc 注释在

Express Response
对象中记录自定义属性和方法。

具体来说,我想向 Response 对象添加自定义

error
success
函数,以一致的方式处理错误响应。

我已经尝试过

@typedef
但它仍然显示此警告,而不是抛出错误 -
Property 'error' may not exist on type 'Response<any, Record<string, any>, number>'

@typedef {object} CustomResponse
@property {Function} error - A function to handle error responses.
/**
 * *Route for handling 404 Not Found errors.
 * *This middleware will catch any request that does not match any other route handlers.
 *
 * @param {import('express').Request} req - The Express request object.
 * @param {import('express').Response} res - The Express response object.
 * @param {import('express').NextFunction} next - The next function to pass control to the next middleware.
 *
 * @date 07 September 2023
 */
app.all('*', (req, res) => {
    return res.error(
        HTTPStatus.NOT_FOUND,
        'The requested resource could not be found but may be available in the future'
    );
});
javascript node.js express jsdoc
1个回答
0
投票

如何使用 TypeScript 中的 Request 对象执行此操作获得灵感...

将 TypeScript 类型定义文件添加到您的项目中。例如,您可以在路径

src/types/express/index.d.ts
处添加一个文件,其内容为:

// to make the file a module and avoid the TypeScript error
export {}

declare global {
  namespace Express {
    export interface Response {
      error: Function;
    }
  }
}

然后,确保您的 jsconfig.json 文件查看 TypeScript 文件

{
  //...
  "include": [
    "**/*.js",
    "**/*.d.ts"
  ]
  //...
}

完成此设置后,VS Code 应该识别出您的

res
变量具有
error
函数。您的
TypeScript
定义文件还可以使用
.js
等语法引用代码库中其他
import('path/to/file/exporting/class.js').default
文件中的类型。

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