Optional Properties Differ From undefined

Optional properties let the whole key go missing, while a required prop of type T or undefined must exist; in checks and spreads tell the two apart.

TypescriptConfig Management

Code

typescriptsnippet
22 lines
interface WatchConfig {
  interval: number;
  // optional property:键可以整个缺失
  labels?: string[];
  // 显式 undefined:键必须在,值允许是 undefined
  endpoint: string | undefined;
}

function show(config: WatchConfig): void {
  // in 判断键是否存在,与值是不是 undefined 无关
  console.log(`labels key present: ${"labels" in config}`);
  console.log(`endpoint key present: ${"endpoint" in config}`);
  console.log(`endpoint value: ${config.endpoint ?? "(unset)"}`);
}

// labels 整个缺省;endpoint 键存在、值为 undefined
show({ interval: 30, endpoint: undefined });

// 展开合并时显式 undefined 会覆盖已有键:键被写入,而不是删掉
const merged = { ...{ endpoint: "edge-a" }, endpoint: undefined };
console.log(`own keys after spread: ${Object.keys(merged).join(",")}`);

Output

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

labels key present: false
endpoint key present: true
endpoint value: (unset)
own keys after spread: endpoint

Inside the code

The snippet is organized around the function show.

Caveats

  • No install step: all APIs used ship with the platform.

Using it

Entry signature: function show(config: WatchConfig)

Look for the labels key present: $, endpoint key present: $, endpoint value: $ prefixes when the file runs; they tie each line to its step.

Key statements

const merged = { ...{ endpoint: "edge-a" }, endpoint: undefined };
show({ interval: 30, endpoint: undefined });
endpoint: string | undefined;

Interactive Tools for This Topic

FAQ

What has to be installed first?
Nothing — the runtime itself provides everything the code touches. The file defines `show` at load time.