使用Typescript接口进行运行时JSON类型检查

这篇博客探讨了在Typescript项目中使用Aegis库进行运行时JSON数据与接口类型检查的需求和实现。作者讨论了避免重复代码和不修改其他生产代码的情况下实现这一目标的挑战,以及在NodeJS、React Native和浏览器环境中应用的考虑。最终,作者选择了Picnic的Aegis工具,并对其进行了适当的调整以适应Bytecode项目,并提出了自动化和工具改进的愿望。
摘要由CSDN通过智能技术生成

This blog was originally posted in Dutch on Bytecode’s Insights and in English on my personal website

该博客最初在 Bytecode的见解中 以荷兰语发布, 在我的 个人网站 上以英语 发布。

Bytecode is currently working on a project for a startup. We are developing an app that is linked to a backend data storage service. For this project, I wanted to have more security around the API calls and validate the types at runtime.

字节码目前正在为启动项目工作。 我们正在开发与后端数据存储服务链接的应用程序。 对于这个项目,我希望在API调用方面具有更高的安全性,并在运行时验证类型。

背景 (Background)

At Bytecode, we use Typescript extensively for front-end and mobile development, to prevent Javascript’s liberal dynamic typing system from causing errors. Typescript adds an extra layer of security. In recent years, we have seen a strong decrease in type-related errors due to the use of Typescript.

在Bytecode,我们将Typescript广泛用于前端和移动开发,以防止Javascript的自由动态键入系统引起错误。 Typescript增加了一层额外的安全性。 近年来,由于使用Typescript,与类型相关的错误已大大减少。

However, Typescript also has it’s limitations, the main one being that types and interfaces disappear during compile-time. So there are no run-time checks on external data that is not available during compilation, like for example API responses. Ideally, Typescript would support marshalling in a way similar to Go, to secure type safety during runtime. Unfortunately, however, the Typescript layer disappears during compile-time and only Javascript remains: code that knows nothing about the types and interfaces defined in the source code. Unfortunately, the Go-like approach would never be possible using features built into the language.

但是,Typescript也有其局限性,主要的原因是类型和接口在编译时会消失。 因此,不会对编译期间不可用的外部数据进行运行时检查,例如API响应。 理想情况下,Typescript将以类似于Go的方式支持编组,以确保运行时的类型安全。 但是,不幸的是,Typescript层在编译时消失了,只剩下Javascript:对源代码中定义的类型和接口一无所知的代码。 不幸的是,使用语言内置的功能永远无法实现类似Go的方法。

Until recently, we did our API calls directly within Redux actions, which didn’t cause any problems for small applications. However, this setup is not the best, considering the single-responsibility principle and keeping in mind that Redux act

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值