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

如何用TypeScript定义接收指定类型子集属性的函数?

解决方案:使用Partial<T>约束属性子集

你需要的是一个仅包含目标类型零个或多个属性、且严格匹配属性类型的参数类型,TypeScript内置的Partial<T>工具类型正好能解决这个问题。

完整代码实现

type Animal = {
  name: string;
  age: number;
  dimensions: number[];
};

// 用Partial<Animal>替代Record<string, any>
type OnlyAnimalProps = Partial<Animal>;

function createAnimal(parent: Animal, props: OnlyAnimalProps) {
   return {...parent, ...props};
}

验证效果

合法调用(TypeScript无报错)

  • 传入空对象:createAnimal(someAnimal, {})
  • 传入单个合法属性:createAnimal(someAnimal, {name: "Cindy"})
  • 传入多个合法属性:createAnimal(someAnimal, {age: 12, dimensions: [1, 3, 2]})

不合法调用(TypeScript直接报错)

  • 传入不存在的属性:createAnimal(someAnimal, {height: 123}) → 提示height不是Animal的属性
  • 传入类型不匹配的属性:createAnimal(someAnimal, {name: 456}) → 提示number类型不能赋值给string类型

补充说明

Partial<T>的作用是将目标类型T的所有属性转换为可选属性,既保证了只能使用T中已有的属性,又允许传入零个或多个属性,完全匹配你的需求。如果需要更严格的场景(比如变量传入时也禁止额外属性),可以结合Pick或自定义严格子集类型,但Partial<T>已经能覆盖绝大多数常见场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 21:20:51