@aarifkhamdi

Как добавить новый тип Request в typing Express?

Я хочу добавить новый тип Request. То есть есть обычный Request, а я хочу сделать свой с новым полем.

Есть вариант сделать просто
declare module 'express-serve-static-core' {
    interface Request {
        auth?: {
            test: string
        }
    }
}

но тогда приходится проверять на undefined

Я написал так, но не могу понять как мне подружить роутинг с добавленным мною типом. Подскажите, пожалуйста?:
declare module 'express-serve-static-core' {
    interface AuthorizedRequest<P extends Params = ParamsDictionary> extends Request<P> {
        auth: {
            test: string
        }
    }
}


spoiler
TSError: ⨯ Unable to compile TypeScript:
src/routers/user.ts:6:19 - error TS2769: No overload matches this call.
Overload 1 of 4, '(path: PathParams, ...handlers: RequestHandler>[]): Express', gave the following error.
Argument of type '(req: AuthorizedRequest>, res: Response) => Promise' is not assignable to parameter of type 'RequestHandler>'.
Types of parameters 'req' and 'req' are incompatible.
Property 'auth' is missing in type 'Request>' but required in type 'AuthorizedRequest>'.
Overload 2 of 4, '(path: PathParams, ...handlers: RequestHandlerParams>[]): Express', gave the following error.
Argument of type '(req: AuthorizedRequest>, res: Response) => Promise' is not assignable to parameter of type 'RequestHandlerParams>'.
Type '(req: AuthorizedRequest>, res: Response) => Promise' is not assignable to type 'RequestHandler>'.
Overload 3 of 4, '(path: PathParams, subApplication: Application): Express', gave the following error.
Argument of type '(req: AuthorizedRequest>, res: Response) => Promise' is not assignable to parameter of type 'Application'.
Type '(req: AuthorizedRequest>, res: Response) => Promise' is missing the following properties from type 'Application': init, defaultConfiguration, engine, set, and 61 more.
  • Вопрос задан
  • 262 просмотра
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы