请求体不符合接口要求,但没有返回错误。

huangapple go评论98阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年8月9日 01:41:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76862002.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定