Home > Blockchain >  How to throw typescript error in express?
How to throw typescript error in express?

Time:04-20

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');
  }
}

CodePudding user response:

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');
  }
}
  • Related