TypeScript&运行时类型检查,2020年的简单解决方案 [英] TypeScript & runtime type-checking, simple solution in 2020

查看:131
本文介绍了TypeScript&运行时类型检查,2020年的简单解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

众所周知,TypeScript仅在编译时进行类型检查.

As we all know, TypeScript type-checks only at compile-time.

有两种添加运行时检查的现有方法,例如 io-ts ,但是我只是想知道是否有更简单的方法.

There are couple of existing approaches to add runtime checks, such as io-ts, but I'm left to wonder if there is a simpler way.

例如会翻译的Babel插件:

For example a Babel plugin that would transpile this:

type Todo = {
  userId: number;
  id: number;
  title: string;
  completed: boolean;
}

const resp = await fetch("https://jsonplaceholder.typicode.com/todos/1");

const data = await resp.json();

assert(data typeof Todo);

对此:

const __TodoType = {
  userId: Number;
  id: Number;
  title: String;
  completed: Boolean;
};
const __isTodoType = obj => (
  obj &&
  obj.constructor === Object &&
  Object.keys(obj).length === Object.keys(__TodoType).length &&
  Object.entries(obj)
    .every(([prop, val]) =>
      __TodoType[prop] && val &&
      __TodoType[prop] === val.constructor)
);

const resp = await fetch("https://jsonplaceholder.typicode.com/todos/1");

const data = await resp.json();

assert(__isTodoType(data));

这将是一个非常简单的解决方案,并将涵盖许多(如果不是大多数)用例. AFAICT,这足以声明序列化/数据获取.

This would be a super simple solution and would cover many (if not most) uses cases. AFAICT, this would be enough for asserting serialization / data fetching.

有人设法构建了这样的Babel插件吗?

Has someone managed to build such Babel plugin?

编辑-我知道现有的库,例如io-ts,但我正在寻找更简单的方法.我展示的Babel插件(到目前为止,从插件用户的角度来看)要简单得多.我不确定为什么以前没有做到这一点.

Edit - I know the existing libraries such as io-ts but I'm looking for something much simpler. The Babel Plugin I'm showcasing is vastly simpler (from the perspective of the plugin user) than anything else I've seen so far. I'm not sure why this hasn't been done before.

推荐答案

我也对此感到沮丧,最终写了我自己的类型保护生成器‛ts-type-checked‛,它可以作为

I was frustrated by this as well and ended up writing my own type guard generator called ‛ts-type-checked‛ available as an NPM module. It is a TypeScript transform that generates type guards based on your types.

这篇关于TypeScript&运行时类型检查,2020年的简单解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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