angular - 跳过 TypeScript 函数中的参数
问题描述
我已经从问题Skip arguments in a JavaScript function中尝试了Pacerier 的答案。但它似乎不起作用。
我有一个有很多参数的函数
this.service.list("all",null, null, localStorage.getItem('currentProgram'), null, 100, ...Array(2), environment.liveMode).subscribe(...)
我发现的唯一方法是一一编写,例如(,null,null或undefined,undefined)。
我还设置了一个测试方法,看看有没有不同,但效果不好。
test(a: any, b: any, c: any, d: string) {
console.log(d)
}
ngOnInit() {
this.test(...Array(3), "a")
}
我还尝试了答案中提出的其他语法。
在 TypeScript 中是否有更简洁的方法来执行此操作?
解决方案
在 TypeScript 中,如果你想跳过一个参数,你必须明确地传递undefined
或null
作为参数值。例子:
function f(param1?: string, param2?: number, param3?: boolean) {
// do something
}
f(,,true); // ❌ Error
f(...[,,], true); // ❌ Error
f(...Array(2), true); // ❌ Error
f(undefined, undefined, true); // ✅ Works
f(null, null, true); // ✅ Works
您可以在 TypeScript 文档的此部分中找到更多信息和示例:https ://www.typescriptlang.org/docs/handbook/2/functions.html#optional-parameters
推荐阅读
- android - 如何使用 sqlite 数据设置多个警报?
- r - 带有 html 标签的 rhandsontable
- go - OpenShift API - 无法使用配置
- css - Flexbox 有问题 2 列 3 项
- java - 拖放后被拖动的物品消失
- python - Wagtail:为 Multisite 中的每个应用程序设置一个专用的静态文件夹
- php - 处理具有相同错误号的 Mysql 错误
- git - 当应该有合法输出时,Git 分支、差异等在终端中没有显示任何输出
- php - 分段错误(核心转储)Laravel SwiftMailer
- php - 为什么这种日期格式会继续更改为 1970-01-01?