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

TypeScript实现Express响应包装器的HTTP参数静态校验问题

解决方案

你遇到的报错核心原因是没有把传入的status参数作为泛型参数捕获其具体值,导致THTTPStatusCodeToData[typeof status]只能拿到所有允许状态码的联合类型,无法匹配到对应映射规则。你可以按照以下方式修改代码实现所需校验规则:

第一步:定义基础类型约束

import type { Response } from 'express'

// 保留你原有的响应键值类型定义
interface IEmbracedResponse {
  payload: Record<string, any>
  error: string
  exception: Error
}

// 定义状态码和对应响应结构的映射关系
interface StatusResponseMap {
  200: Pick<IEmbracedResponse, 'payload'>
  400: Pick<IEmbracedResponse, 'error'>
  500: Pick<IEmbracedResponse, 'exception'>
  // 可根据业务需求拓展更多状态码对应的结构
}

// 提取允许传入的状态码类型
type AllowedStatusCode = keyof StatusResponseMap

第二步:修改包装函数实现

把状态码作为泛型参数引入,自动关联对应响应结构的校验规则:

function responseWrapper<S extends AllowedStatusCode>(
  res: Response,
  status: S,
  data: StatusResponseMap[S]
) {
  return res.status(status).json(data)
}

效果验证

你期望的所有校验规则都可以自动生效:

// 校验不通过的场景(TS会直接报错)
responseWrapper(res, 200, { exception: Error('ups') }); 
responseWrapper(res, 500, { exception: 'something crashed'}); 
responseWrapper(res, 200, { something: null}); 
responseWrapper(res, 500, { error: 'ups' }); 

// 校验通过的场景
responseWrapper(res, 200, { payload: { isAdmin: true }}); 
responseWrapper(res, 500, { exception: Error('ups') }); 
responseWrapper(res, 400, { error: 'ups' }); 

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 23:45:08