通过键数组筛选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
相关产品推荐
相关产品推荐

