【问题标题】:Declaration merging doesn't work with express 4.17.* Request type声明合并不适用于 express 4.17.* 请求类型
【发布时间】:2020-11-15 23:05:12
【问题描述】:

我想为 Request 类型添加一个属性,因此我创建了一个文件夹 @types/express 并在此文件夹中添加了包含此内容的文件 index.d.ts。

namespace Express {
  interface Request {
    user: number;
  }
}

在 VSCode 中,当我引用 req.user 时,错误消失了,它甚至显示 user 的类型为 number screenshot that shows that "user" property on the "Request" object is treated right

但是当我启动服务器时,我看到了这样的错误:

/home/myself/web/my-server/node_modules/ts-node/src/index.ts:434
    return new TSError(diagnosticText, diagnosticCodes)
           ^
TSError: ⨯ Unable to compile TypeScript:
src/app.ts:46:7 - error TS2339: Property 'user' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs>'.

46   req.user;
         ~~~~

    at createTSError (/home/myself/web/my-server/node_modules/ts-node/src/index.ts:434:12)
    at reportTSError (/home/myself/web/my-server/node_modules/ts-node/src/index.ts:438:19)
    at getOutput (/home/myself/web/my-server/node_modules/ts-node/src/index.ts:578:36)
    at Object.compile (/home/myself/web/my-server/node_modules/ts-node/src/index.ts:775:32)
    at Module.m._compile (/home/myself/web/my-server/node_modules/ts-node/src/index.ts:858:43)
    at Module._extensions..js (internal/modules/cjs/loader.js:1220:10)
    at Object.require.extensions.<computed> [as .ts] (/home/myself/web/my-server/node_modules/ts-node/src/index.ts:861:12)
    at Module.load (internal/modules/cjs/loader.js:1049:32)
    at Function.Module._load (internal/modules/cjs/loader.js:937:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)

如果有任何关于如何解决它的想法,我将不胜感激。

附言我对express-session 模块做了同样的事情,并在Session 接口中添加了一个counter 属性,它可以完美运行

【问题讨论】:

    标签: node.js typescript express definitelytyped


    【解决方案1】:

    安装了@types/express@types/express-session 也足够了),这应该可以工作:

    index.d.ts

    declare module '@types/express-serve-static-core' {
      interface Request {
        user?: User
      }
    }
    

    重要的部分是声明合并逻辑是@types/express-serve-static-core 的一部分(参见https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/express-serve-static-core/index.d.ts)。

    【讨论】:

      【解决方案2】:

      在失去一些脑细胞后,我为自己提供了答案。 为了解决这个问题,我必须重新创建可以在这个问题中找到的文件夹结构 https://github.com/microsoft/TypeScript/issues/39581

      然后我修改了 tsconfig.json,使它的 typeRoots 看起来像这样

       "typeRoots": [
            "src/typings/",
            "node_modules/@types/"
          ] 
      

      然后,为了用我的自定义类型增加 Request 类型,我必须使用 import 表达式,所以最后 index.d.ts 文件里面会有这个

      declare namespace Express {
        export interface Request {
          user: import("mongoose").Model<import("./../../models/user").User>;
        }
      }
      

      为 cmets 中的人配置 tsconfig

      {
        "compilerOptions": {
                     /* Enable incremental compilation */
          "target": "es5" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */,
          "module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */,
          "lib": [
            "es6"
          ] /* Specify library files to be included in the compilation. */,
          "allowJs": true /* Allow javascript files to be compiled. */,
                           /* Concatenate and emit output to single file. */
          "outDir": "build" /* Redirect output structure to the directory. */,
          "rootDir": "src" /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */,
          "strict": true /* Enable all strict type-checking options. */,
          "noImplicitAny": true /* Raise error on expressions and declarations with an implied 'any' type. */,
                           /* List of root folders whose combined content represents the structure of the project at runtime. */
          "typeRoots": [
            "src/typings/",
            "node_modules/@types/"
          ] /* List of folders to include type definitions from. */,
          "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
      
          /* Advanced Options */
          "resolveJsonModule": true /* Include modules imported with '.json' extension */,
          "skipLibCheck": true /* Skip type checking of declaration files. */,
          "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
        }
      }
      
      

      【讨论】:

      • 你能发布你的 tsconfig 吗?我根本无法让它工作
      • @foxtrotuniform6969 我已将其添加到帖子中
      猜你喜欢
      • 2020-11-05
      • 2021-07-08
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 2013-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多