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

如何定义类似Record<A,B>且允许省略属性、不接受undefined值的TS类型?

解决方案

要实现允许省略指定键集中的任意键,但禁止将存在的键值设为undefined的类型,我们可以定义如下的StrictPartialRecord类型:

type StrictPartialRecord<K extends keyof any, T> = {
  [P in keyof any]: P extends K ? T : never;
};

示例验证

我们用你的测试场景来验证这个类型:

type A = 'A1' | 'A2' | 'A3';

// 合法:仅包含A1键,值为string类型
const valid1: StrictPartialRecord<A, string> = { A1: 'value for A1' };

// 合法:包含A1和A2键,值均为string类型
const valid2: StrictPartialRecord<A, string> = { A1: 'value for A1', A2: 'value for A2' };

// 合法:空对象
const valid3: StrictPartialRecord<A, string> = {};

// 非法:A1的值为undefined,不符合string类型要求
const invalid1: StrictPartialRecord<A, string> = { A1: undefined };

// 非法:A2的值为undefined,不符合string类型要求
const invalid2: StrictPartialRecord<A, string> = { A1: 'value for A1', A2: undefined };

// 非法:包含不在A中的键A4
const invalid3: StrictPartialRecord<A, string> = { A4: 'value for A4' };

工作原理

这个类型通过以下方式实现需求:

  • 使用[P in keyof any]定义通用索引签名,覆盖所有可能的键类型(字符串、数字、符号)。
  • 对于每个键P,如果它属于指定的键集K,则要求其值类型为T;否则将值类型设为never,直接禁止使用不在K中的键。
  • 由于T不包含undefined(除非显式传入T | undefined),因此任何存在的键都必须赋值为T类型的值,从根源上排除了undefined的情况。

这样既满足了允许省略任意键的需求,又严格禁止了将键值设为undefined的行为,完全符合场景要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 14:49:50