发布于 2026-01-06 0 阅读
0

JS 中使用 invariant 的守卫

JS 中使用 invariant 的守卫

引言

你听过这句话吗?👇

如果你想成为最优秀的人,那就向最优秀的人学习。

我认为这与编程技能非常契合💻

所以在本系列教程中,我们将逐步从著名的开源项目中学习一流的JS!

👉 今日主题 - 使用不变式的守卫 🛡️

守卫(Guard)是处理错误和防止代码出现 bug 的绝佳方法。
结合不变式(Invariant),它将成为一种更强大、更通用的技术 💪

👉 首先,什么是保安?

守卫只是验证:

  • 警卫检查特定情况
  • 如果条件为真,则该守卫会阻止某些功能执行。
function handleInput(input) {
  const isInvalid = !input || typeof input !== 'string';

  // Here it is!
  if (isInvalid) {
    throw new Error('Input is invalid');
  }

  return getProcessedInput(input);
}
Enter fullscreen mode Exit fullscreen mode

👉 好的,我会用它们的!

使用这种守卫方式存在一个问题。
它迫使你在几十个地方重复抛出 `throw new Error`。
例如,如果你想添加简单的日志记录,就必须更新所有地方的所有守卫。

function handleInput(input) {
  const isInvalid = !input || typeof input !== 'string';

  if (isInvalid) {
    console.log('Input is invalid'); // <- add this in all places  
    throw new Error('Input is invalid');
  }

  return getProcessedInput(input);
}
Enter fullscreen mode Exit fullscreen mode

👉 如何像顶尖人才一样做到这一点?

React 开发人员也遇到了同样的问题,并添加了特殊的无变量抽象来解决这个问题。

它在保持 DRY 原则的同时,实现了同样的功能。

function handleInput(input) {
  const isValid = input && typeof input === 'string';

  invariant(isValid, 'Input is invalid');

  return getProcessedInput(input);
}
Enter fullscreen mode Exit fullscreen mode

👉 不变式在底层是如何工作的?

最流行的 JS 不变式实现接受多个参数:

  • 该条件定义了是否需要抛出错误。
  • 简而言之,就是错误信息的格式
  • 六个可选参数,用于代替格式中的 %s。
invariant(
  1 > 2, 
  'Hello from error. %s %s %s %s %s %s',
  1, 2, 3, 4, 5, 6
);

// Results to
// > Uncaught Error: Hello from error. 1 2 3 4 5 6
Enter fullscreen mode Exit fullscreen mode

👉 让我们重新实现它!

和往常一样,让我们​​自己重新创造不变性,以深入了解其内部运作机制。

我们的版本采用现代 ES6+ 语法,并支持不定数量的可选参数。

const invariant = (condition, format, ...args) => {
  if (!condition) {
    if (!format) {
      throw new Error('General error occured.');
    }

    let i = 0;

    throw new Error(format.replace(/%s/g, () => args[i++]));
  }
};
Enter fullscreen mode Exit fullscreen mode

👉 自己动手实现吧!

请到我的 CodeSandbox中,根据我们刚刚学到的知识,尝试实现不变函数。


PS:请在Twitter上关注我,获取更多类似内容!

文章来源:https://dev.to/fromaline/guards-using-invariant-in-js-24kk