英文:
Request body doesn't comply with interface, but doesn't return error
问题
我有一个名为NewTransactionPayload的接口,我希望确保我的请求体只包含这个对象。但是,显然,在托管时,TypeScript没有任何投诉。为什么呢?
// 接口
interface NewTransactionPayload {
transactionAmount: Number;
transactionDate: String;
transactionWallet: String;
transactionPocket: String;
transactionTag: String;
transactionDetails: String;
}
transactionsRouter.post('/', (req, res)=>{
try {
const newTransaction:NewTransactionPayload = req.body;
// const newTransaction = body;
res.status(201).json(newTransaction);
} catch (err){
res.status(400).json({error: `Bad request. ${err}`})
}
});
英文:
I have this NewTransactionPayload interface, whereby I want to make sure that my request body only contains this object. But apparently, upon hosting, I don't see any complaint from TypeScript. Why?
// interfaces
interface NewTransactionPayload {
transactionAmount: Number;
transactionDate: String;
transactionWallet: String;
transactionPocket: String;
transactionTag: String;
transactionDetails: String;
}
transactionsRouter.post('/', (req, res)=>{
try {
const newTransaction:NewTransactionPayload = req.body;
// const newTransaction = body;
res.status(201).json(newTransaction);
} catch (err){
res.status(400).json({error: `Bad request. ${err}`})
}
});
答案1
得分: 3
TypeScript是JavaScript的一种带类型的超集,旨在在编译时捕获错误。这意味着TypeScript可以在代码执行之前检测到语法错误和类型安全性违规,有助于防止运行时错误。
然而,TypeScript不执行运行时类型检查。这是因为在编译过程中,变量和表达式的类型被移除。这样做是为了提高性能,因为运行时类型检查可能会增加开销。
如果您需要执行运行时类型检查,可以使用第三方库,例如Zod。Zod是一个为TypeScript提供运行时类型验证的库。它可以用于在运行时验证变量、表达式和对象的类型。
参考:https://www.totaltypescript.com/tutorials/zod/zod-section/number
英文:
TypeScript is a typed superset of JavaScript that is designed to catch errors at compile time. This means that TypeScript can detect syntax errors and type safety violations before your code is executed, which can help to prevent runtime errors.
However, TypeScript does not perform runtime type checking. This is because the types of variables and expressions are removed during compilation. This is done to improve performance, as runtime type checking can add overhead.
If you need to perform runtime type checking, you can use a third-party library like Zod. Zod is a library that provides runtime type validation for TypeScript. It can be used to validate the types of variables, expressions, and objects at runtime.
Ref: https://www.totaltypescript.com/tutorials/zod/zod-section/number
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论