【问题标题】:How to require a group of optional parameters when an argument is provided for just one of the parameters?当只为其中一个参数提供参数时,如何要求一组可选参数?
【发布时间】:2022-01-04 22:40:25
【问题描述】:

我有一个带有可选参数的函数

export const sentryException = (
  error: Error,
  contextLabel?: string,
  contextInfo?: Context,
  specificTags?: SentryTags,
) => {

如图所示,最后 3 个是可选的。但是,如果提供了contextLabel,则必须提供contextInfo。我宁愿不必这样做

if ((contextLabel && !contextInfo) || (contextInfo && !contextLabel)) {
   // throw error
}

您可以想象,随着所需输入分组数量的增加,这可能会变得非常混乱!

如果提供了特定参数,是否有任何方法要求必须在函数调用中传递可选参数的子集?


编辑: 我只是想清楚// throw error 注释与error 参数无关。我的意思是contextLabelcontextInfo 必须始终都被定义(而不是undefined);否则,该函数应该无法执行。

所以为了简单起见,我们假设所有类型都是字符串,除了error,那么有效的调用将是:

sentryException(err, 'a', 'b')
sentryException(err, 'a', 'b', 'c')
sentryException(err, undefined, undefined, 'c')
sentryException(err)

【问题讨论】:

  • 那个if条件是一个简单的异或,可以用if (contextInfo !== contextLabel)表示

标签: typescript optional-parameters


【解决方案1】:

听起来像是一组简单的function overloads 的工作,您可以在其中创建所需的特定参数类型配对:

function sentryException(
  contextLabel?: undefined,
  contextInfo?: undefined,
  specificTags?: string,
): void

function sentryException(
  contextLabel: string,
  contextInfo: string,
  specificTags?: string,
): void

function sentryException(
  contextLabel?: string,
  contextInfo?: string,
  specificTags?: string,
): void {
  // implementation...
}

// good
sentryException()
sentryException(undefined, undefined, 'tag')
sentryException('a', 'b', 'tag')

// errors
sentryException('a')
sentryException('a', undefined, 'tag')

Playground

【讨论】:

  • 文档中的示例令人困惑。当我运行console.log(d3) 时,即使提供了两个值,它仍然会打印。我在 IDE 中看到有一个错误,但它并没有阻止它运行。这意味着,在本示例的上下文中,我仍然必须提供某种逻辑,或多或少地表示“如果提供了两个参数,则在忽略第二个参数的情况下调用该函数”。
  • 类型错误不会阻止您的代码转译为 javascript。它只会转译有类型错误。我工作的应用程序有一个自动检查来查找类型错误,如果有,那么代码将不会部署到服务器。如果您将类型错误视为关键,那么这不是问题。如果您希望此代码可以从普通 JS 中使用,您可以只希望他们正确阅读文档,或者您可以添加运行时检查以引发无效输入。但是当一切都是纯打字稿时,类型错误应该足以停止在生产中使用它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-21
  • 1970-01-01
  • 2012-06-23
  • 1970-01-01
  • 2019-02-24
  • 1970-01-01
  • 2011-10-16
相关资源
最近更新 更多