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

通过键数组筛选TypeScript接口类型的实现方案

TypeScript 实现根据指定键数组返回对应类型的对象

给定如下TypeScript接口:

interface Human {
    name: string;
    age: number;
    height: number;
}

需要实现一个函数,接收该接口的键组成的数组,返回仅包含这些指定键的对象,且TypeScript能根据输入的键数组自动推断返回对象的类型——只有传入的键可以被访问,未传入的键会触发类型错误。

你之前的泛型写法存在语法错误,正确的实现方式如下:

const getPartialHuman = <T extends keyof Human>(keys: T[]): Pick<Human, T> => {
  // 假设有一个预先定义的Human实例对象
  const human: Human = { name: "Alice", age: 25, height: 165 };
  
  return keys.reduce((acc, key) => {
    acc[key] = human[key];
    return acc;
  }, {} as Pick<Human, T>);
};

代码说明:

  • 泛型T被约束为keyof Human,表示T是Human接口键的子集(联合类型)
  • 参数keys的类型是T[],传入的数组元素必须是Human的键,TS会根据传入的数组自动推断出T的具体联合类型
  • 返回值使用Pick<Human, T>,表示从Human中挑选出T对应的键值对组成的新类型
  • 实现逻辑中用reduce遍历键数组,从原human对象中提取对应属性,通过类型断言将初始空对象指定为Pick<Human, T>,确保类型匹配

使用示例:

const partial = getPartialHuman(["name", "age"]);
console.log(partial.name); // 正常访问,无类型错误
console.log(partial.age); // 正常访问,无类型错误
console.log(partial.height); // 类型错误:height属性不存在于Pick<Human, "name" | "age">类型上

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 23:53:25