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

如何用TypeScript映射类型保留非下划线开头的属性?

提取TypeScript类型中不以下划线开头的属性

当然可以实现,利用TypeScript的映射类型和键重映射(Key Remapping)语法就能做到,核心思路是遍历原类型的所有属性,过滤掉以下划线开头的键。

核心实现代码

// 示例原类型
type T = {
  a: string,
  _a: string,
  b: number,
  _c: boolean,
  d: symbol,
  /* 任意数量的未知属性 */
};

// 定义映射类型过滤下划线开头的属性
type RemoveUnderscorePrefix<T> = {
  [K in keyof T as K extends `_${string}` ? never : K]: T[K]
};

// 测试结果
type FilteredType = RemoveUnderscorePrefix<T>;
// FilteredType 的最终类型为:{ a: string; b: number; d: symbol; }

代码说明

  • [K in keyof T]:遍历原类型T的所有属性键
  • as K extends _${string} ? never : K:这是TypeScript 4.1+支持的键重映射语法,用来筛选属性:
    • 通过模板字面量类型_${string}匹配以下划线开头的字符串键
    • 如果匹配成功,返回never会排除该属性;否则保留原键K
  • T[K]:保留原属性对应的类型

扩展处理非字符串键

如果原类型包含number或symbol类型的键,上面的逻辑会直接保留这些键(因为它们不匹配字符串模板_${string})。如果需要明确只过滤字符串类型中下划线开头的键,可以调整条件:

type RemoveUnderscorePrefix<T> = {
  [K in keyof T as K extends string ? (K extends `_${string}` ? never : K) : K]: T[K]
};

这样number/symbol类型的键会被完整保留,仅排除字符串类型里以下划线开头的属性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 00:46:14