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

TypeScript中如何将API请求体转指定类型并过滤缺失字段?

要解决这个问题,核心是只保留原请求体中实际存在的字段,同时完成指定类型的转换(比如groupid转ObjectId、arc转Date),下面提供两种实用的实现方案:

方案一:手动判断可选字段(适合字段较少的场景)

这种方式代码直观,逐个检查原对象是否包含可选字段,存在才添加到目标对象中:

import { ObjectId } from 'mongodb'; // 假设使用mongodb的ObjectId

export type aircraft = {
  _id?: ObjectId,
  groupid: ObjectId,
  reg: string,
  type?: string,
  desc?: string,
  arc?: Date,
}

export function addAircraft(newAircraft: any) {
  // 先初始化必填字段,确保类型转换正确
  const insertAircraft: Partial<aircraft> = {
    reg: newAircraft.reg,
    groupid: new ObjectId(newAircraft.groupid)
  };

  // 只添加原请求体中存在的可选字段
  if ('type' in newAircraft) {
    insertAircraft.type = newAircraft.type;
  }
  if ('desc' in newAircraft) {
    insertAircraft.desc = newAircraft.desc;
  }
  if ('arc' in newAircraft) {
    // 转换为Date对象,额外过滤无效日期
    const arcDate = new Date(newAircraft.arc);
    if (!isNaN(arcDate.getTime())) {
      insertAircraft.arc = arcDate;
    }
  }

  // 断言为aircraft类型,因必填字段已确保存在
  return insertAircraft as aircraft;
}

方案二:通用遍历处理(适合字段较多的场景)

如果aircraft类型的可选字段较多,用遍历的方式更简洁,避免重复的if判断:

import { ObjectId } from 'mongodb';

export type aircraft = {
  _id?: ObjectId,
  groupid: ObjectId,
  reg: string,
  type?: string,
  desc?: string,
  arc?: Date,
}

export function addAircraft(newAircraft: any) {
  const insertAircraft: Partial<aircraft> = {};

  // 处理必填字段,若API可能传入缺失的必填字段,建议在此处加校验逻辑
  insertAircraft.reg = newAircraft.reg;
  insertAircraft.groupid = new ObjectId(newAircraft.groupid);

  // 定义允许保留的可选字段列表
  const allowedOptionalFields = ['type', 'desc', 'arc'] as const;

  // 遍历原对象的键值对,筛选并转换字段
  Object.entries(newAircraft).forEach(([key, value]) => {
    if (allowedOptionalFields.includes(key as typeof allowedOptionalFields[number])) {
      if (key === 'arc') {
        // 处理日期转换,过滤无效日期
        const date = new Date(value);
        if (!isNaN(date.getTime())) {
          (insertAircraft as any)[key] = date;
        }
      } else {
        (insertAircraft as any)[key] = value;
      }
    }
  });

  return insertAircraft as aircraft;
}

关键说明

  • 使用Partial<aircraft>允许目标对象先只包含部分字段,最后通过类型断言转为aircraft(前提是确保必填字段已存在)。
  • 对于日期字段arc,添加了isNaN(date.getTime())的判断,避免无效日期转换后得到Invalid Date的情况。
  • 两种方案都会严格只保留原请求体中存在的字段,不会额外添加null或undefined的字段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 21:00:50