← 中文资源

简体中文版本

用 Record<PropertyKey, never> 约束真正的空对象

区分 {}、object 与 Record<PropertyKey, never>:{} 会放过数字和字符串,object 允许任意键,只有把 PropertyKey 映射到 never 才代表真正空对象。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

nonNullish type: number | nonPrimitive keys: 1
merged: {"traceId":"tr-901"}

实现说明

活动部件是函数 attachMeta。 返回值是携带 base 的对象。

使用要点

  • 唯一的前提是这个语言自己的工具链。
  • 跑完文件,输出里会留下标记——nonNullish type:、merged:。

常见问题

attachMeta 会修改传入的参数吗?

入参保持不变;拿回来的是新建的值。

除了语言工具链还要下载什么吗?

除了这个语言的工具链,什么都不用再下载。 文件在加载时定义 attachMeta。

主签名形如 function attachMeta(base: EmptyObject, meta: RequestMeta)

核心语句

return { ...base, ...meta };

代码示例

// `{}` matches any non-nullish value, including numbers and strings
const anyNonNullish: {} = 42;

// `object` rejects primitives, but still allows arbitrary properties
const nonPrimitive: object = { extra: true };

// `Record<PropertyKey, never>` forbids all keys while accepting `{}`
type EmptyObject = Record<PropertyKey, never>;

interface RequestMeta {
  traceId: string;
}

function attachMeta(base: EmptyObject, meta: RequestMeta): RequestMeta {
  return { ...base, ...meta };
}

const empty: EmptyObject = {};
// const badNum: EmptyObject = 42;         // Type error: number is not EmptyObject
// const badProp: EmptyObject = { a: 1 };  // Type error: property 'a' is incompatible with never

console.log('nonNullish type:', typeof anyNonNullish, '| nonPrimitive keys:', Object.keys(nonPrimitive).length);
console.log('merged:', JSON.stringify(attachMeta(empty, { traceId: 'tr-901' })));