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

如何基于TypeScript类型定义高效提取对象指定字段?

问题描述

给定以下两个TypeScript类型:

type AllValues = {
  a: string;
  b: string;
  c: string;
  d: string;
  e: string;
  f: string;
  g: string;
};

type SomeValues = {
  b: string;
  d: String;
  f: string;
  g: string;
};

以及一个包含全量字段的对象:

const allValues: AllValues = {
  a: "Some value",
  b: "Some value",
  c: "Some value",
  d: "Some value",
  e: "Some value",
  f: "Some value",
  g: "Some value",
}

是否存在无需手动编写赋值代码的方式,从该全量对象中提取出仅包含SomeValues类型定义字段的新对象?

解决方案

当然可以,借助TypeScript的类型工具和自定义工具函数就能实现自动提取,不用逐个字段手动赋值:

方法1:通用提取工具函数(结合keyof类型)

先实现一个通用的字段提取函数,利用TypeScript的类型约束确保提取的字段属于源对象的键:

function pick<T, K extends keyof T>(obj: T, keys: K[]): Pick<T, K> {
  const result = {} as Pick<T, K>;
  keys.forEach(key => {
    result[key] = obj[key];
  });
  return result;
}

// 使用示例
const someValues = pick(allValues, ['b', 'd', 'f', 'g']);

此时someValues会被自动推断为Pick<AllValues, 'b'|'d'|'f'|'g'>,和你定义的SomeValues类型几乎一致。需要注意:你的SomeValues中d的类型是大写的String(包装对象类型),而AllValues里是小写string(原始类型),类型层面存在差异,建议统一为小写string避免兼容问题。

方法2:严格对齐SomeValues类型的提取

如果要完全匹配SomeValues类型,可以先提取其键类型,再用工具函数提取:

type SomeKeys = keyof SomeValues;
const someKeys: SomeKeys[] = ['b', 'd', 'f', 'g'];

const someValues: SomeValues = pick(allValues, someKeys);

如果SomeValues和AllValues存在字段类型不一致的情况(比如d的String和string),需要确保源对象字段可以兼容,或者手动处理类型转换。

额外提示

  • 尽量避免在TypeScript中使用大写String类型,通常小写string(原始类型)是更标准的选择,两者运行时兼容但类型层面会有差异。
  • 如果不想自己实现工具函数,也可以使用lodash.pick这类第三方库,TypeScript会自动推断提取后的类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 12:22:29