首页 > 解决方案 > 如何将自定义请求类型添加到 Express?

问题描述

我想添加自定义请求类型来表达。

有办法只扩展请求。但是我必须检查的这种方式是未定义的身份验证。

我找不到如何将 AuthorizedRequest 与 app.get('/path/, ...) 一起使用

如何正确声明 AuthorizedRequest?

// need to check undefined, auth can not exists so i cant remove "?"
declare module 'express-serve-static-core' {
    interface Request {
        auth?: {
            test: string
        }
    }
}

// error with routing app.get(...)
declare module 'express-serve-static-core' {
    interface AuthorizedRequest<P extends Params = ParamsDictionary> extends Request<P> {
        auth: {
            test: string
        }
    }
}

但我收到以下错误:

“- 错误 TS2769:没有与此调用匹配的重载。”

标签: typescript-typings

解决方案


  1. 创造./typings/index.d.ts
  2. 设置 tsconfig:"typeRoots": ["./typings", "./node_modules/@types"]

index.d.ts 示例:

type Params = {
    test1: {
        test2: string
    },
    test3: number
}

declare global {
    namespace Express {
        export interface Request extends Params {}
    }
}

declare module 'express' {
    export type ExtendableRequest = Request<any, any, any, any> & 
}

export {}

推荐阅读