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

TypeScript类型编程:校验对象至少包含两个字段

TypeScript工具类型:校验对象至少包含两个字段

要实现这个校验逻辑,我们可以利用TypeScript的条件类型、keyof操作符和Exclude工具类型来完成,具体实现如下:

type ObjectWithAtLeastTwoFields<T extends object> = 
  keyof T extends infer K 
    ? (K extends keyof T 
      ? Exclude<keyof T, K> extends never 
        ? never 
        : T 
      : never) 
    : never;

逻辑说明:

  • 提取键的联合类型:通过keyof T获取输入对象所有键的联合类型,并用infer K将其提取出来。
  • 触发分布式遍历:通过K extends keyof T触发分布式条件类型,遍历联合类型中的每个键。
  • 判断键的数量:用Exclude<keyof T, K>移除当前遍历到的键,如果移除后结果为never,说明原对象只有0个或1个键,返回never;反之则说明至少有两个键,返回原对象类型T。

测试验证

type A = ObjectWithAtLeastTwoFields<{ a: 0, b: 1 }> // { a: 0, b: 1 }
type B = ObjectWithAtLeastTwoFields<{ a: 0 }> // never
type C = ObjectWithAtLeastTwoFields<{}> // never

内容的提问来源于stack exchange,提问作者Carl Patenaude Poulin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 06:27:22