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

如何基于Type类型移除TypeScript对象中的多余属性?

TypeScript中动态移除扩展类型的额外属性

要实现一个能自动移除继承自Entity的类型中额外属性的convert函数,同时避免硬编码检查特定键(因为Entity可能会变更),可以按以下方式处理:

核心思路

TypeScript的类型信息在编译后会被擦除,所以必须将Entity的键信息保留到运行时。我们可以把Entity的键定义为一个常量数组,再通过这个数组推导Entity类型,这样后续修改键数组就能同步更新类型,无需两处维护。

实现代码

// 定义Entity的键列表(运行时可用)
const entityKeys = ['id', 'code'] as const;

// 通过键数组推导Entity类型
type Entity = {
  [K in typeof entityKeys[number]]: K extends 'id' ? string : number;
};

// 实现convert函数:只保留Entity中定义的属性
const convert = <E extends Entity>(presentable: E): Entity => {
  return entityKeys.reduce((result, key) => {
    result[key] = presentable[key];
    return result;
  }, {} as Entity);
};

// 测试示例
const converted1 = convert({ id: '10', code: 100 }); 
// 输出:{ id: '10', code: 100 }

const converted2 = convert({ id: '5', code: 200, label: 'My label', name: 'My name' }); 
// 输出:{ id: '5', code: 200 }

补充说明

如果更倾向于先定义Entity接口,再手动维护对应的键数组,也可以这么写:

interface Entity {
  id: string;
  code: number;
}

// 手动维护与Entity对应的键数组
const entityKeys: (keyof Entity)[] = ['id', 'code'];

const convert = <E extends Entity>(presentable: E): Entity => {
  return entityKeys.reduce((result, key) => {
    result[key] = presentable[key];
    return result;
  }, {} as Entity);
};

这种方式需要确保键数组和接口定义完全一致,否则可能出现运行时错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 03:55:12