实现说明
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);