← 中文资源

简体中文版本

KeysOfUnion 收集联合全键

keyof 作用在联合上只得到各成员共有的键;分布式的条件类型 KeysOfUnion 才能收集全部键,运行时用 Object.keys 求并集可交叉验证。

阅读英文原文

运行结果

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

shared key: kind
all keys sample: label
runtime keys: [ 'height', 'kind', 'label', 'radius', 'width' ]
kind on every shape: true

实现说明

除了函数 runtimeKeys,文件里再无其他定义。 返回的是新建的值,不复用入参。

使用要点

  • 直接运行文件,输出会带上标签,比如 shared key:、all keys sample:、runtime keys:——输出的每一行都能指回产生它的那次调用。

常见问题

runtimeKeys 会修改传入的参数吗?

不会修改。入参只读,返回值是全新构造的。

这个示例需要哪些包?

一个都不用。代码用到的符号都在标准库里解析。 文件在加载时定义 runtimeKeys。

入口签名:function runtimeKeys(shapes: readonly Shape[])

核心语句

return [...new Set(shapes.flatMap((shape) => Object.keys(shape)))].sort();
type KeysOfUnion<T> = T extends object ? keyof T : never;
type SharedKeys = keyof Shape;

代码示例

interface Circle {
  readonly kind: "circle";
  readonly radius: number;
}
interface Rect {
  readonly kind: "rect";
  readonly width: number;
  readonly height: number;
  readonly label: string;
}
type Shape = Circle | Rect;

// keyof over a union yields only the keys shared by every member
type SharedKeys = keyof Shape;

// The distributive conditional collects every key across all members
type KeysOfUnion<T> = T extends object ? keyof T : never;
type AllKeys = KeysOfUnion<Shape>;

// Compile-time proof of both behaviors
const shared: SharedKeys = "kind";
const all: AllKeys = "label";

// Runtime counterpart: union the own keys of each shape
function runtimeKeys(shapes: readonly Shape[]): string[] {
  return [...new Set(shapes.flatMap((shape) => Object.keys(shape)))].sort();
}

const sample: readonly Shape[] = [
  { kind: "circle", radius: 2 },
  { kind: "rect", width: 3, height: 4, label: "board" },
];
console.log("shared key:", shared);
console.log("all keys sample:", all);
console.log("runtime keys:", runtimeKeys(sample));
console.log("kind on every shape:", sample.every((shape) => "kind" in shape));