KeysOfUnion Across Union Members

Collect every key across a union of shapes with a distributive conditional - plain keyof only exposes the keys every member shares.

TypescriptData Integrity

Code

typescriptsnippet
36 lines
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));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

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

How the file behaves

The parts that matter are the function runtimeKeys — everything else is wiring.

It builds and returns a fresh value rather than reusing its inputs.

Points of care

  • Only the runtime is required — no packages, no install.

Using it

Signature: function runtimeKeys(shapes: readonly Shape[])

The run emits 4 labeled sections — shared key:, all keys sample:, runtime keys:, kind on every shape: — one per step.

Key statements

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

Interactive Tools for This Topic

FAQ

Does `runtimeKeys` modify its input?
It does not. Inputs are only read; the return value is freshly built.
Which packages does this snippet need?
None. Every symbol the code uses resolves inside the standard library. The file defines `runtimeKeys` at load time.