在TypeScript中对未类型化的数据强制执行类型 [英] Enforcing types on untyped data in TypeScript

查看:233
本文介绍了在TypeScript中对未类型化的数据强制执行类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道使用TypeScript时是否有任何工具或技术用于对对象数据进行低级验证.一个示例是HTTP服务上POST请求的JSON正文.通常,我已经为预期的数据创建了一个接口,然后将数据投射到该接口,但是我知道这是肤浅的.

I'm wondering if there are any tools or techniques that are being used to do low level validation on object data when using TypeScript. An example would be a JSON body of a POST request on a HTTP service. Typically I've created an interface for the expected data and then cast the data to that interface but I'm aware that this is superficial.

示例:

router.route('/supercres')
    .get((req, res, next) => {
        const typedBody = <SuperCresBody>req.body;
    })

interface SuperCresBody {
    name: string,
    yoyo: boolean,
}

强制接口的问题是TypeScript只是一个编译时概念,在运行时不执行任何操作.知道这一点,我很想知道是否有人找到了一个聪明的方法而没有大量的样板程序或工具,以便在运行时对这些事情进行类型检查,而不必将接口协定作为一组必要的检查重复进行,以作为验证步骤.

The problem with enforcing the interface is that TypeScript is just a compile-time concept and does not enforce anything at runtime. Knowing this I'm curious if anybody has found a clever way without a lot of boilerplate or tooling in order to pull off type checking at runtime for these things without having to repeat the interface contract as a set of imperative checks as a validation step.

有点相关的注释中,在最新功能性怪胎,马蒂亚斯·费莱森(Matthias Felleisen)解释了情节尾端附近的类型拍"的类似需求.

On a somewhat related note, in the most recent episode of Functional Geekery, Matthias Felleisen explains a similar need in Typed Racket near the tail end of the episode.

相关阅读:

推荐答案

检查这两个等效项目:

  • https://github.com/gcanti/io-ts
  • https://github.com/pelotom/runtypes

我使用的是最新版本,它可以完美运行,但是前者看起来也很棒.

I use the latest, it works flawlessly, but the former looks awesome as well.

在两种情况下,您都会构建用于以下目的的验证器:

In both cases, you build a validator that you use to:

  • 在运行时检查对象
  • 提取可在编译时使用的静态类型

在特定的(api)用例中,您还可以使用一些工具从产生的JSON或XML中提取TS类型

In your specific (api) use case, you can also use some tooling to extract TS types form the JSON or XML you produce

您还可以轻松地从JSON数据生成类型:

You can also generate typings easily from JSON data:

http://json2ts.com/

这篇关于在TypeScript中对未类型化的数据强制执行类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆