跳到主要内容

趣味盎然:JSON To Sarcastic类型 — Numio

根据 JSON 示例为 sarcastic 运行时类型检查库生成校验器。对象变为 is.shape({...}),数组变为 is.arrayOf(...),数组中部分元素缺少的键用 is.maybe(...) 包裹。

在不使用 schema 库的小型 JavaScript 项目中,于运行时检查获取到的 JSON 结构。

JSON

Sarcastic

适用场景

  • 在不使用 schema 库的小型 JavaScript 项目中,于运行时检查获取到的 JSON 结构。
  • 用遇到意外数据时抛出异常的断言保护配置或消息载荷。

使用方法

  1. 粘贴 JSON 对象;要把字段标记为可选,请包含有该字段和没有该字段的数组元素。
  2. 查看输出:根 shape 为 RootInterface,嵌套 shape 按键名命名(posts 变为 Posts)。
  3. 复制代码,用 is(data, RootInterface) 校验数据,它在匹配时返回该值,不匹配时抛出异常。

JSON 输入

{
  "id": 1,
  "name": "Ada",
  "nickname": null,
  "tags": ["math"],
  "posts": [
    { "title": "Notes", "draft": true },
    { "title": "Engine" }
  ]
}

Sarcastic 校验器

import is from "sarcastic"

const anyValue = (value) => value

const Posts = is.shape({
  title: is.string,
  draft: is.maybe(is.boolean),
})

const RootInterface = is.shape({
  id: is.number,
  name: is.string,
  nickname: is.maybe(anyValue),
  tags: is.arrayOf(is.string),
  posts: is.arrayOf(Posts),
})

功能与限制

在浏览器中由本站自己的生成器生成,自动添加 import is from "sarcastic" 并用 Prettier 格式化;不发起服务器请求。

sarcastic 没有 "any" 断言,因此始终为 null 的值变为 is.maybe(anyValue),并在输出中添加一个小的辅助函数 const anyValue = (value) => value。

整数和小数都是 is.number。空数组变为 is.array;混合数组使用 is.either,例如 is.arrayOf(is.either(is.number, is.string))。

shape 在使用它们的 shape 之前声明,因此代码粘贴后即可运行。

FAQ

可选字段如何表示?

在同一数组的部分对象中缺失或为 null 的键用 is.maybe(...) 包裹,它接受 null 和 undefined。单个对象的顶层键始终是必需的。

根节点为数组时会怎样?

元素会合并为一个描述单个元素的 RootInterface shape,并添加表示整个数组的 const RootInterfaceList = is.arrayOf(RootInterface)。

sarcastic 和 io-ts 或 Zod 一样吗?

不一样。sarcastic 是更小的库,没有静态类型推断。如果还需要 TypeScript 类型,JSON 转 Zod 或 JSON 转 io-ts 页面更合适。

规范与参考资料