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

TypeScript类型断言后仍有多余字段?如何正确转换为DTO

TypeScript中如何将含多余字段的JSON转换为纯净DTO

你用<UserDTO>jsonData这种类型断言后,运行时输出仍保留city字段是因为:TypeScript的类型系统仅作用于编译阶段——类型断言只是让编译器把对象当作UserDTO类型处理,但不会在运行时修改原对象的结构,多余字段自然不会被自动删除。

要实现“去除无关字段,得到结构严格匹配DTO的对象”,必须在运行时手动处理,以下是几种实用方案:

方案1:手动提取所需字段

最直接的方式,明确取出DTO定义的字段:

interface UserDTO {
    name: string;
    age: number;
}

const jsonData = {
    name: "John",
    age: 30,
    city: "New York",
};

const user: UserDTO = {
  name: jsonData.name,
  age: jsonData.age
};

console.log(user); // 输出: { name: 'John', age: 30 }

方案2:通用字段提取函数

如果需要处理多个不同DTO,可以封装通用函数避免重复代码:

interface UserDTO {
    name: string;
    age: number;
}

const jsonData = {
    name: "John",
    age: 30,
    city: "New York",
};

// 通用函数:从对象中提取指定字段
function pick<T>(obj: any, requiredKeys: (keyof T)[]): T {
  const result = {} as T;
  requiredKeys.forEach(key => {
    if (obj[key] !== undefined) {
      result[key] = obj[key];
    }
  });
  return result;
}

// 使用时传入DTO类型和需要保留的字段
const user = pick<UserDTO>(jsonData, ['name', 'age']);
console.log(user); // 输出: { name: 'John', age: 30 }

方案3:解构赋值过滤

利用ES6解构赋值的剩余语法,快速剔除多余字段:

interface UserDTO {
    name: string;
    age: number;
}

const jsonData = {
    name: "John",
    age: 30,
    city: "New York",
};

// 解构出不需要的字段,剩余部分就是符合DTO的对象
const { city, ...user } = jsonData;
console.log(user); // 输出: { name: 'John', age: 30 }

以上三种方案都能在运行时真正去除多余字段,让最终对象结构完全匹配你的DTO定义。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 01:02:40