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

256
Visualizações
How to throw typescript error in express?

I created a typescript class controller. I intentionally passed a missing property which is "email" in the payload. And I wonder why its not throwing a typescript error like "email(undefined) is not equals to email(string)".

The problem is it did not literally throwed an error because it proceeds executing "console.log". My expectation is, it should not proceed the execution since it did not meet to type "testType" (correct me if i'm wrong).

May I know your thoughts on how to achieve this one?


type testType = {
  body: {
    email: string
    password: string
  }
}

class Testing {
  public static sampleFunc = async (req: testType, res: Response, next: NextFunction) => {
    const temp = req.body
    
    console.log('temp', temp);

    // ..more code here
    
    res.send('success');
  }
}
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Typescript is used for static type checking and is compiled to javascript. Therefore, at runtime you're actually running the compiled javascript code, and as such you cannot rely on typescript to protect you against passing properties with incorrect type.

To achieve what you want, you need to add some additional error checking in the code before you process the request.

Something like:

class Testing {
  public static sampleFunc = async (req: testType, res: Response, next: NextFunction) => {    
    if (!req.email || !req.password) {
      throw new Error("No email / password provided");
    }
    
    res.send('success');
  }
}
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