【问题标题】:How to extend express.Request with tsserver + JSDoc?如何使用 tsserver + JSDoc 扩展 express.Request?
【发布时间】:2021-10-20 13:00:01
【问题描述】:

我在一个 JavaScript 项目中在 vim 中使用了 tsserverJSDoc。我遇到了以下问题:

/** @type {import('express').Handler} */
function requireUser(req, res, next) {
  if (!req.user) {
    throw new Error("Unauthorized");
  }
  next();
}

这是错误:

[tsserver] Property 'user' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'. [E]

当然,我的代码中有数百个地方引用了req.user

这是我目前的tsconfig.json,供参考:

{
  "compilerOptions": {
    "target": "es2021",
   "module": "commonjs",
    "allowJs": true,
    "checkJs": true,
    "noEmit": true,
    "strict": true,
    "alwaysStrict": true,
    "noUnusedLocals": true,
    "typeRoots": ["./@types", "./node_modules/@types"],
    "esModuleInterop": true,
    "preserveSymlinks": false,
    "maxNodeModuleJsDepth": 20,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["src/**/*.js"],
  "exclude": ["node_modules"]
}

我尝试在./@types/types.d.ts 中放置一个文件,其中包含整个namespace Express 位用于Typescript 声明合并,但它似乎没有生效。

【问题讨论】:

    标签: node.js typescript jsdoc tsserver


    【解决方案1】:

    完整的解释在这里:

    https://github.com/BeyondCodeBootcamp/jsdoc-typescript-starter

    简而言之:

    tsconfig.json:

    {
        "compilerOptions": {
            "typeRoots": ["./typings", "./node_modules/@types"],
            "...": ""
        },
        "...": ""
    }
    

    ./typings/express/index.d.ts:

    // You can extend other types that you modify with middleware.
    declare namespace Express {
      // Here we tell the linter to expect `user`, `authn`, and `query`
      // to exist on Request objects, and a custom `result` handler to
      // exist on Response objects.
      export interface Request {
        query: Record<string, string>;
        user?: User;
        authn?: any;
      }
    
      // Here we tell the linter about our special alternative to
      // res.result
      export interface Response {
        result?: (result: any) => void;
      }
    

    【讨论】:

      猜你喜欢
      • 2021-08-10
      • 2016-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-16
      • 2020-07-15
      • 1970-01-01
      • 2015-07-21
      相关资源
      最近更新 更多