我试图添加一个属性来表达使用typescript从中间件请求对象。但是,我不知道如何向对象添加额外的属性。如果可能的话,我宁愿不用括号。

我正在寻找一个解决方案,允许我写类似的东西(如果可能的话):

app.use((req, res, next) => {
    req.property = setProperty(); 
    next();
});

当前回答

如果您正在寻找与express4一起工作的解决方案,下面是:

@types /快递/ index.d。--------必须是/index.d.ts

declare namespace Express { // must be namespace, and not declare module "Express" { 
  export interface Request {
    user: any;
  }
}

tsconfig.json:

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es2016",
    "typeRoots" : [
      "@types", // custom merged types must be first in a list
      "node_modules/@types",
    ]
  }
}

参考资料来自https://github.com/TypeStrong/ts-node/issues/715#issuecomment-526757308

其他回答

对于较新的express版本,您需要增强express- service -static-core模块。

这是必需的,因为现在Express对象来自那里:https://github.com/DefinitelyTyped/DefinitelyTyped/blob/8fb0e959c2c7529b5fa4793a44b41b797ae671b9/types/express/index.d.ts#L19

基本上,使用以下方法:

declare module 'express-serve-static-core' {
  interface Request {
    myField?: string
  }
  interface Response {
    myField?: string
  }
}

这就是我在使用Nestjs和Express时的工作方式。截至2020年11月。

创建一个文件:./@types/express- server -static-core/index.d.ts

注意:必须有上面的路径和文件名。这样Typescript声明合并就可以了。

import { UserModel } from "../../src/user/user.model";

declare global{
    namespace Express {
        interface Request {
            currentUser: UserModel
        }
    }
}

将其添加到tsconfig.json中

"typeRoots": [
      "@types",
      "./node_modules/@types",
    ]        

只需将属性添加到req。params对象。

req.params.foo = "bar"

在mac节点12.19.0和express 4上,使用护照进行身份验证,我需要扩展我的Session对象

与上面相似,但略有不同:

import { Request } from "express";


declare global {
  namespace Express {
    export interface Session {
      passport: any;
      participantIds: any;
      uniqueId: string;
    }
    export interface Request {
      session: Session;
    }
  }
}

export interface Context {
  req: Request;
  user?: any;
}```

如果你尝试了所有的答案,仍然没有得到工作,这里有一个简单的hack

app.use((req, res, next) => {
    (req as any).property = setProperty(); 
    next();
});

这将把req对象转换为任意类型,因此您可以添加任何想要的属性。 请记住,这样做将失去req对象的类型安全性。