← 中文资源

简体中文版本

多余属性检查守护配置字面量

用接口约束字面量形式的配置对象:拼错的键在编译期报错;而来自更宽类型变量的赋值不触发多余键检查,两种边界的差异一目了然。

阅读英文原文

运行结果

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

valid config: { region: 'eu-central-1', replicas: 3, tls: true }
widened from variable: { region: 'us-east-1', replicas: 2, debug: true }

实现说明

raw 定义在模块顶层,中间不经过函数作用域。 一个对象字面量承载 region、replicas、tls——每个值都就地写死。

使用要点

  • 跑完文件,输出里会留下标记——valid config:、widened from variable:。

常见问题

除了语言运行时还需要什么准备?

什么都不需要——语言运行时是唯一要求。 文件用顶层绑定保存自己的状态:raw。

核心语句

const widened: DeployConfig = raw; // structural match, no extra-key error
console.log('widened from variable:', widened);
const raw = { region: 'us-east-1', replicas: 2, debug: true };
replicas: number;

代码示例

interface DeployConfig {
  region: string;
  replicas: number;
  tls?: boolean;
}

// Fresh object literals get excess property checking:
// every declared key must exist and no unknown key may appear.
const config: DeployConfig = {
  region: 'eu-central-1',
  replicas: 3,
  tls: true,
};
console.log('valid config:', config);

// A misspelled key on a fresh literal fails compilation:
// "Object literal may only specify known properties, and 'replcas' does not
// exist in type 'DeployConfig'." The typo never reaches runtime.

// Excess checks target fresh literals, not wider variables:
const raw = { region: 'us-east-1', replicas: 2, debug: true };
const widened: DeployConfig = raw; // structural match, no extra-key error
console.log('widened from variable:', widened);