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