如何在TypeScript中从对象剔除指定Interface定义的属性?
实现方法
首先要明确:TypeScript 的接口仅存在于编译阶段,运行时无法直接通过接口获取属性列表,因此我们需要手动维护对应属性的键数组,同时借助 keyof 确保类型安全。
贴合你需求的实现(保留指定接口属性,剔除额外属性)
你的示例中,实际需求是保留 Needed 接口定义的属性、去掉对象中额外的 boolVal,可以这样写:
interface Needed { intVal: number; stringVal: string; } const obj = { intVal: 0, stringVal: 'string', boolVal: true, }; // 定义对应 Needed 接口的属性键数组,用 keyof 确保类型匹配 const neededKeys: Array<keyof Needed> = ['intVal', 'stringVal']; // 遍历保留的键,构建结果对象 const resultObj = neededKeys.reduce((acc, key) => { acc[key] = obj[key]; return acc; }, {} as Needed); console.log(resultObj); // 输出:{ intVal: 0, stringVal: 'string' }
补充:若需剔除指定接口的属性
如果你的 NotNeeded 接口实际包含要剔除的属性(比如 { boolVal: boolean }),可以用以下方式实现:
interface NotNeeded { boolVal: boolean; } const obj = { intVal: 0, stringVal: 'string', boolVal: true, }; const notNeededKeys: Array<keyof NotNeeded> = ['boolVal']; // 过滤掉不需要的属性,构建结果对象 const resultObj = Object.fromEntries( Object.entries(obj).filter(([key]) => !notNeededKeys.includes(key as keyof NotNeeded)) ) as { intVal: number; stringVal: string }; console.log(resultObj); // 输出:{ intVal: 0, stringVal: 'string' }
注:你的示例中 Needed 和 NotNeeded 接口属性完全一致,这会导致「剔除 NotNeeded 属性」的结果是空对象,显然和你期望的结果不符,因此推测你实际需求是保留 Needed 接口的属性,上述第一种方法更贴合你的目标。
内容的提问来源于stack exchange,提问作者Sergei Lobanov
相关产品推荐
相关产品推荐

