← 中文资源

简体中文版本

用 const 快照在闭包内保留类型收窄

演示可变 let 绑定在回调函数内丢失类型收窄的原因,并通过在守卫分支后捕获 const 快照,将非空类型安全带入延迟执行。

阅读英文原文

运行结果

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

immediate prefix: tok_
cleared outer let: undefined
skipped: missing token
queued result: verified:TOK_ALPHA

实现说明

除了函数 scheduleValidation,文件里再无其他定义。 for (const run of tasks) 是唯一的迭代点——其余代码顺序执行一遍。 入参 queue 会被原地修改——调用方若要保留原值需先拷贝。

使用要点

  • 外部扩展面始终为零:全部程序逻辑均源于语言内置标准库。
  • 演示输出是带标签的(skipped: missing token、immediate prefix:、cleared outer let:),每个操作都会留下自己的一行标注。
  • queue 是原地修改,传进去的值之后就不一样了。

常见问题

scheduleValidation 会修改传入的参数吗?

会——queue 被原地修改。调用方需要保留原值时请先拷贝。

运行前要先安装什么?

什么都不用额外装——运行时自带了代码所需的一切。 文件在加载时定义 scheduleValidation。

主签名形如 function scheduleValidation( source: TokenSource, queue: Array<()

核心语句

queue.push(() => `verified:${stableToken.toUpperCase()}`);
const tasks: Array<() => string> = [];

代码示例

interface TokenSource {
  current?: string;
}

function scheduleValidation(
  source: TokenSource,
  queue: Array<() => string>,
): void {
  let token = source.current;
  if (token === undefined) {
    console.log('skipped: missing token');
    return;
  }

  // Directly here, `token` is narrowed to `string`
  console.log('immediate prefix:', token.slice(0, 4));

  // Inside a closure, TypeScript widens `let token` back to `string | undefined`
  // queue.push(() => token.toUpperCase()); // Compile error: 'token' is possibly 'undefined'

  // Capture an immutable `const` snapshot so deferred closures keep `string`
  const stableToken = token;
  queue.push(() => `verified:${stableToken.toUpperCase()}`);

  // Mutating the outer `let` proves why the closure needed its own `const` snapshot
  token = undefined;
  console.log('cleared outer let:', String(token));
}

const tasks: Array<() => string> = [];
scheduleValidation({ current: 'tok_alpha' }, tasks);
scheduleValidation({}, tasks);

for (const run of tasks) {
  console.log('queued result:', run());
}