You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否利用TypeScript类型自动验证JSON对象?免手动编写类型守卫

如何自动校验API响应体是否符合TypeScript定义的类型?

问题描述

我第一次用TypeScript开发API,习惯为API的response.body定义预期类型,示例如下:

type ApiProps = {
  name: string
  email: string
}

现在我想确认response.body是否属于ApiProps类型的对象,但发现必须手动编写类型守卫来完成所有字段校验。有没有办法避免这种重复的手动校验?比如实现这样的通用类型守卫函数:

function hasValidProps<T>(body: unknown): body is T {
  // 自动基于类型定义完成校验的逻辑
}

可行解决方案(2022年状态)

当时这个需求还无法直接通过TypeScript原生特性实现,但我找到了一个实用的方案:

function hasValidProps<T extends Record<string, unknown> = Record<string, unknown>>(
  body: unknown,
  props: T
): body is T {
  try {
    const bodyObject = JSON.parse(body as string) as Record<string, unknown>
    const bodyObjectKeys = Object.keys(bodyObject)
    const isValid = Object.keys(props).every((key) => bodyObjectKeys.includes(key))
    if (isValid) {
      body = bodyObject
    }
    return isValid
  } catch {
    return false
  }
}

const apiProps = {
  name: '',
  email: ''
}

export type ApiProps = typeof apiProps

// 在API校验流程中使用:
if (!hasValidProps<ApiProps>(request.body, apiProps)) {
    response.status(400).end()
    return
}

内容的提问来源于stack exchange,提问作者Nicolas Bouvrette

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 08:40:33