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

如何实现TypeScript工具类型PickPropertyTypes提取指定类型的接口属性?

如何实现根据属性类型挑选对象属性的TypeScript工具类型?

完全可行,你可以通过TypeScript的映射类型+条件类型组合,实现这个和Pick逻辑互补的PickPropertyTypes工具类型——它根据属性的类型筛选,而非指定具体属性名。

实现代码

首先定义工具类型:

type PickPropertyTypes<T, TargetType> = {
  // 遍历原类型的所有键,仅保留属性类型匹配TargetType的键
  [Key in keyof T as T[Key] extends TargetType ? Key : never]: T[Key]
};

结合你的示例验证

用你给出的interface A测试:

interface A {
  a: string;
  b: number;
  c: string[];
  d: { [key: string]: never };
}

// 基于A筛选出属性类型为string或number的成员
interface B extends PickPropertyTypes<A, string | number> {}

此时B的最终结构完全符合你的预期:

{
  a: string;
  b: number;
}

额外说明

  • 这个实现依赖TypeScript 4.1及以上版本的键重映射(as语法),确保你的项目TS版本达标
  • 如果需要严格的类型匹配(而非"可赋值"兼容),可以调整条件判断逻辑:
    type PickExactPropertyTypes<T, TargetType> = {
      [Key in keyof T as T[Key] extends TargetType 
        ? (TargetType extends T[Key] ? Key : never) 
        : never]: T[Key]
    };
    
    这种写法会排除那些"目标类型是属性类型的父类"的情况,比如避免把string | number类型的属性误选入string目标类型中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 19:51:02