实现说明
可选属性与显式 undefined 的差异以函数 show为骨架。
常见问题
运行前要先安装什么?
什么都不用额外装——运行时自带了代码所需的一切。 文件在加载时定义 show。
主签名形如 function show(config: WatchConfig)
核心语句
const merged = { ...{ endpoint: "edge-a" }, endpoint: undefined };
show({ interval: 30, endpoint: undefined });
endpoint: string | undefined;
代码示例
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(",")}`);