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

TypeScript中如何按类型从Child实例提取Parent接口的全部属性?

核心原因说明

TypeScript 是编译时类型系统,所有接口、类型注解仅在编译阶段做校验,不会生成任何运行时代码。你尝试的解构写法仅会对child对象做全量拷贝,附加的类型注解只会做类型校验,不会自动过滤不属于Parent的属性,因此无法达到预期效果。


可行实现方案

方案1:属性量少,手动维护属性键列表

如果Parent的属性不多,直接手动定义键数组遍历提取即可,写法简单易维护:

// 用as const + satisfies保证类型安全,修改Parent属性时漏改这里会直接报编译错误
const parentKeys = ['prop1', 'prop2'] as const satisfies Array<keyof Parent>;

function magicFunctionToGetAllParentProperties(child: Child): Parent {
  const parentProps = {} as Parent;
  for (const key of parentKeys) {
    parentProps[key] = child[key];
  }
  return parentProps;
}

方案2:属性量多,统一维护类型定义避免重复编码

如果Parent属性较多,或者不想重复写两遍属性定义(一次接口、一次键数组),可以用运行时类型校验库统一维护结构,同时获得自动过滤能力:

import { z } from 'zod';

// 仅需维护一次Parent结构,同时生成TS类型和运行时校验规则
const ParentSchema = z.object({
  prop1: z.string(),
  prop2: z.string()
});
type Parent = z.infer<typeof ParentSchema>;

// 基于Parent扩展Child结构
const ChildSchema = ParentSchema.extend({
  prop3: z.string(),
  prop4: z.string(),
  // ... 其余属性
  prop100: z.string()
});
type Child = z.infer<typeof ChildSchema>;

// Zod的parse方法会自动过滤掉不在ParentSchema内的属性
function magicFunctionToGetAllParentProperties(child: Child): Parent {
  return ParentSchema.parse(child);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 19:18:03