Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

402
Visualizações
How can I handle type with middleware of express?

I am using Typescript in Node.js. When you use Express middleware, you often transform the Request object. With Typescript, however, we could not track how the Request object was transformed. If you know the middleware that passed before, is there a way to find out the type of the request from it? If not possible in express, I would like to find another framework where it is possible. Is it possible in Nest (https://github.com/kamilmysliwiec/nest)?

Example Code

import { Request, Response, NextFunction } from 'express';

function userMiddleware(req: Request & User, res: Response, next: NextFunction) {
    req.user = {
        id: 'user_id',
    };
    next();
}

interface User {
    user: {
        id: string;
    }
}

interface Middleware {
    <T>(req: Request & T, res: Response, next: NextFunction): void;
}

class Controller {
    middleware = [userMiddleware];

    get = new GetMethod(this.middleware);

    post = (req: Request /* I don't know exact req type */, res: Response, next: NextFunction) => {
        console.log(req.user) // Error!
    }
}

class GetMethod {
    constructor(middleware: Middleware[]) {
        // How to deduce type of req from Middleware array?
    }
}

const controller = new Controller();

express.use('/', controller.middleware, controller.post);

I want to extract type information from Middleware list in Controller class.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

First I think the right interface is

interface User {
  id: string;
}

Because they're callbacks they'll receive default Request that don't have user in its signature.

Therefore you have 2 options, do a type assertion, or to write a custom declaration. Both a fine if you do them properly.


Type assertion:

interface User {
  id: string;
}

const isObject = (value: unknown): value is {[key: string]: unknown} => {
  return value && typeof value === 'object';
};

const isReqWithUser = (req: Request): req is Request & {user: User} => {
  return isObject(req) && !!req.user;
}

class Controller {
  post = (req: Request, res: Response, next: NextFunction) => {
    if (isReqWithUser(req)) {
      console.log(req.user) // now it works
    }
    next();
  }
}

Custom declaration:

but we need to understand that user not always exist on the request and we should mark it optional.

interface User {
  id: string;
}

declare module 'express' {
  export interface Request {
    user?: User; // adding our custom declaration.
  }
}

class Controller {
  post = (req: Request, res: Response, next: NextFunction) => {
    console.log(req.user) // now it works
    next();
  }
}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda