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.
Code
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: endpointInside 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
Properties File ParserParse Java .properties files with comments, continuations, separators, and escapes, then emit clean JSON.Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.
FAQ
- What has to be installed first?
- Nothing — the runtime itself provides everything the code touches. The file defines `show` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.