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

如何在TypeScript中强制对象必须包含至少一个属性?

解决TypeScript中禁止空对象的类型定义问题

你可以通过条件类型筛选排除空对象的情况,修改Data类型的定义如下:

type NonEmptyObject<T> = T extends {} ? keyof T extends never ? never : T : never;
type Data = NonEmptyObject<Record<string, string | number | boolean | null>>;

测试验证

const emptyObj: Data = {}; // 触发类型错误,符合预期
const validObj1: Data = { name: "张三" }; // 正常通过
const validObj2: Data = { age: 25 }; // 正常通过
const validObj3: Data = { isEnabled: true }; // 正常通过
const validObj4: Data = { value: null }; // 正常通过

原理说明

  • NonEmptyObject<T>是一个工具类型,它通过条件判断筛选出非空的对象类型:如果传入的T是空对象(keyof T为never),则返回never,否则返回原类型T。
  • 将原本的Record<string, string | number | boolean | null>传入这个工具类型,就得到了禁止空对象赋值的Data类型。

你也可以把逻辑合并成一个更简洁的类型定义,效果完全一致:

type Data = Record<string, string | number | boolean | null> extends infer T 
  ? T extends {} 
    ? keyof T extends never 
      ? never 
      : T 
    : never 
  : never;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 00:33:20