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

如何在TypeScript中提取对象真值属性对应的键创建自定义类型

实现方案

首先你需要给bigObject添加as const断言,让TypeScript能获取到每个属性的精确字面量类型,才能做后续的真值判断:

const bigObject = {
  propA: "sup",
  propB: "hi",
  propC: undefined,
  propD: "",
  propE: "hello",
  propF: null,
} as const;

接着定义提取真值键的工具类型,再构造你需要的目标类型:

// 工具类型:提取对象中值为真值的键集合
type TruthyKeys<T> = {
  [K in keyof T]: T[K] extends false | 0 | '' | null | undefined ? never : K
}[keyof T];

// 方案1:保留原属性值类型,仅保留真值对应的属性
type LittleObject = Pick<typeof bigObject, TruthyKeys<typeof bigObject>>;

// 方案2:如果需要将属性值设为number,按如下写法
type LittleObjectWithNumber = {
  [K in TruthyKeys<typeof bigObject>]: number
};

此时得到的LittleObject/LittleObjectWithNumber的合法键仅有propA、propB、propE,符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 02:30:05