0

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

/** @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 ExpressTypescript 声明合并,但它似乎没有生效。

4

1 回答 1

0

完整的解释在这里:

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-27T19:57:34.773 回答