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

TypeScript如何从类型定义中过滤数组及复杂对象类型的属性

该需求完全可以实现,你只需要调整原有键筛选逻辑,同时匹配数组、普通对象两类需要排除的类型即可。

完整实现代码

// 筛选出所有需要排除的属性键:值为数组或普通对象的键
type ExcludedKeys<T> = { 
  [K in keyof T]: T[K] extends Array<any> | object ? K : never 
}[keyof T];

interface MyInterface {
    a: number;
    b: string;
    c: string;
    d: string[];
    e: number[];
    f: { 
        g: number;
        h: string;
    }
}

type FilteredType = Omit<MyInterface, ExcludedKeys<MyInterface>>;

此时得到的FilteredType会自动过滤所有数组和对象属性,等价于以下结构:

interface FilteredType {
    a: number;
    b: string;
    c: string;
}

特殊场景调整

如果你需要保留函数类型的属性,不希望把函数也一同过滤,可以调整判断逻辑区分普通对象和函数:

type ExcludedKeys<T> = { 
  [K in keyof T]: 
    T[K] extends Array<any> ? K :
    T[K] extends object ? (T[K] extends Function ? never : K) :
    never
}[keyof T];

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 20:36:03