如何在 express 中抛出打字稿错误?
How to throw typescript error in express?
我创建了一个打字稿 class 控制器。我故意传递了一个缺失的 属性 ,它是有效负载中的“电子邮件”。我想知道为什么它不抛出像 "email(undefined) is not equals to email(string)".
这样的打字稿错误
问题是它并没有真正抛出错误,因为它继续执行“console.log”。我的期望是,它不应该继续执行,因为它不满足键入“testType”(如果我错了请纠正我)。
我可以知道您对如何实现这一目标的想法吗?
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');
}
}
Typescript 用于静态类型检查并被编译为 javascript。因此,在运行时你实际上是 运行 编译的 javascript 代码,因此你不能依赖打字稿来保护你免受传递不正确类型的属性。
要实现您想要的效果,您需要在处理请求之前在代码中添加一些额外的错误检查。
类似于:
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');
}
}
我创建了一个打字稿 class 控制器。我故意传递了一个缺失的 属性 ,它是有效负载中的“电子邮件”。我想知道为什么它不抛出像 "email(undefined) is not equals to email(string)".
这样的打字稿错误问题是它并没有真正抛出错误,因为它继续执行“console.log”。我的期望是,它不应该继续执行,因为它不满足键入“testType”(如果我错了请纠正我)。
我可以知道您对如何实现这一目标的想法吗?
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');
}
}
Typescript 用于静态类型检查并被编译为 javascript。因此,在运行时你实际上是 运行 编译的 javascript 代码,因此你不能依赖打字稿来保护你免受传递不正确类型的属性。
要实现您想要的效果,您需要在处理请求之前在代码中添加一些额外的错误检查。
类似于:
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');
}
}