如何在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
相关产品推荐
相关产品推荐

