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

TypeScript中如何基于目标接口自动删除对象多余属性?

解决方案:运行时过滤对象属性以匹配类B的定义

因为TypeScript的类型检查仅在编译阶段生效,运行时对象依然保留了原始类A的所有属性,所以必须通过运行时逻辑过滤出类B定义的属性,以下是几种现成的实现方式:

1. 手动维护属性列表(简单直接)

手动定义类B的属性名数组,通过遍历过滤对象:

class A {
  name?: string;
  family: string;
}

class B {
  name?: string;
}

// 维护类B的属性列表
const B_PROPERTY_NAMES = ['name'] as const;

function filterToB<T extends B>(obj: any): T {
  return B_PROPERTY_NAMES.reduce((result, key) => {
    if (key in obj) {
      result[key] = obj[key];
    }
    return result;
  }, {} as T);
}

// 使用示例
const aInstance = new A();
aInstance.name = "Alice";
aInstance.family = "Smith";

const bTyped: B = aInstance;
const filteredB = filterToB(bTyped);
// filteredB 仅包含 name 属性,可直接用于SQL插入

2. 从类原型自动提取属性(无需手动维护列表)

如果类B是通过class关键字定义而非接口,可以从类的原型中自动获取实例属性(排除constructor):

function filterToB<T extends B>(obj: any): T {
  // 获取类B原型上的所有自有属性,排除构造函数
  const bProps = Object.getOwnPropertyNames(B.prototype).filter(prop => prop !== 'constructor');
  
  return bProps.reduce((result, key) => {
    if (key in obj) {
      result[key as keyof T] = obj[key];
    }
    return result;
  }, {} as T);
}

注意:这种方式仅对类字段定义的属性有效,若B是接口则无法使用(接口编译后不存在原型信息)。

3. 装饰器+元数据(适合复杂场景)

通过装饰器标记类B的属性,运行时读取元数据自动过滤,无需手动维护属性列表,但需要启用TypeScript的实验性装饰器配置:

首先安装依赖:npm install reflect-metadata

然后实现代码:

import 'reflect-metadata';

// 定义装饰器,标记需要保留的属性
function Include() {
  return (target: any, propertyKey: string) => {
    const existingProps = Reflect.getMetadata('includedProps', target.constructor) || [];
    Reflect.defineMetadata('includedProps', [...existingProps, propertyKey], target.constructor);
  };
}

class B {
  @Include()
  name?: string;
}

function filterToB<T extends B>(obj: any): T {
  const includedProps = Reflect.getMetadata('includedProps', B) as string[];
  
  return includedProps.reduce((result, key) => {
    if (key in obj) {
      result[key as keyof T] = obj[key];
    }
    return result;
  }, {} as T);
}

这种方式的优势是修改类B的属性时,过滤规则会自动更新,无需手动调整属性列表。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 00:10:20