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

TypeScript实现带键重映射的Pick工具:自动移除键名$后缀

实现方案

第一步:定义后缀处理工具类型

// 移除字符串末尾的$后缀
type RemoveStreamSuffix<S extends string> = S extends `${infer P}$` ? P : never;

第二步:定义带键重映射的pick函数

function pick<T, K extends RemoveStreamSuffix<keyof T & string>>(x: T, keys: K[]) {
  const result = {} as { [P in K]: T[`${P}$` & keyof T] };
  for (const key of keys) {
    const suffixedKey = `${key}$` as keyof T;
    if (Object.prototype.hasOwnProperty.call(x, suffixedKey)) {
      result[key] = x[suffixedKey];
    }
  }
  return result;
}

使用效果验证

用你给出的demo测试:

let demo: {
  one$: number
  two$: string
} = { one$: 1, two$: '2' };

let result = pick(demo, ['one']);
// result的类型自动推导为 { one: number }
// 运行时值为 { one: 1 }

原理解释

  • RemoveStreamSuffix<keyof T & string>:会遍历原对象所有的键,把带$后缀的键去掉$,得到允许传入的无后缀键联合类型,传入非法键时TS会直接报错提示。
  • 返回类型{ [P in K]: T[${P}$ & keyof T] }:将传入的无后缀键重新映射,匹配原对象中对应加$后缀的属性类型,最终返回的对象键就是传入的无后缀格式。

如果需要兼容原对象中同时存在不带$的键,可调整RemoveStreamSuffix和泛型约束的逻辑,上述实现完全匹配你提出的需求场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 20:09:00